Compare commits

...

26 Commits

Author SHA1 Message Date
edgar e49dde10e7 Distinguir diagnósticos en la ruta de tamizaje 2026-12-02 20:19:36 -06:00
edgar 2dec5af826 Distinguir tiempos de diagnóstico en indicadores 2026-12-02 20:19:36 -06:00
edgar 0316966374 Ajustar la prueba de las escalas al título sin versión 2026-12-02 19:43:55 -06:00
edgar 3d72c153c5 Ficha: quitar la nota de las etapas de la citología 2026-12-02 19:42:55 -06:00
edgar 422b408e37 Ficha: quitar la procedencia del formulario de citología 2026-12-02 19:42:53 -06:00
edgar 211f02edad Ficha: mostrar el VPH como estudio aparte 2026-12-02 19:42:51 -06:00
edgar 32b879edd2 Ficha: mostrar la tabla de modelos como desplegable 2026-12-02 19:42:48 -06:00
edgar 9726d6faa3 Ficha: quitar el texto de las curvas de probabilidad 2026-12-02 19:42:46 -06:00
edgar bafd6760d4 Ficha: llevar la comparación y sus filtros a las curvas de probabilidad 2026-12-02 19:42:43 -06:00
edgar 0666ce3077 Ficha: no mostrar la comparación de riesgos de referencia 2026-12-02 19:42:41 -06:00
edgar d2eada9385 Ficha: titular cada riesgo por su desenlace y llevar el escenario al pie 2026-12-02 19:42:38 -06:00
edgar 0d458818b5 Ficha: dibujar el intervalo sobre la escala y llevar la fecha índice al pie 2026-12-02 19:42:36 -06:00
edgar 2970ce16b0 Ficha: quitar el título Riesgos y recomendaciones 2026-12-02 19:42:33 -06:00
Angel Capetillo Zavala a43cf4b51b Distinguir ausencias e insuficiencia en supervivencia CaCu 2026-12-02 19:26:50 -06:00
edgar a4cc80fbe2 Mostrar la elegibilidad CaCu solo cuando la paciente no es elegible 2026-12-02 19:04:00 -06:00
Angel Capetillo Zavala 370da43695 Agregar elegibilidad CaCu por escenario clínico 2026-12-02 18:47:09 -06:00
edgar f7fdab950a Comparar series de riesgo seleccionables en la ficha CaCu 2026-12-02 18:24:33 -06:00
edgar 1260e0ff2a Mostrar métodos y escenarios sin curva en la supervivencia de la ficha 2026-12-02 18:14:19 -06:00
Angel Capetillo Zavala 09e5f4dd34 CaCu record: grouped NCI comparison, Spanish outcome names, survival texts and risk-only scales
The NCI comparison shows the reference once per horizon and one block per model, saying the
reasons that every incompatible comparison shares only once. Outcome names are translated for
display only (the API identifiers stay), and the reference outcome is read from the answer.
The CaCu survival card is titled as survival and states that its curves estimate the clinical
scenario's group, not an individual. Survival and recurrence estimates no longer feed the risk
scales, curves, probability table or PDF.
2026-12-02 17:48:03 -06:00
Angel Capetillo Zavala f119ba048a Simplify CaCu distribution descriptions 2026-12-02 14:09:02 -06:00
edgar 9ae8254dee Mostrar el motivo de exclusión en la ficha CaCu 2026-12-02 09:35:25 -06:00
Angel Capetillo Zavala b9e210d825 Merge the CaMa diagnostic pathway and biopsy results into the CaCu rounds, record and risk work 2026-12-01 19:02:02 -06:00
Angel Capetillo Zavala 652fd45c29 CaCu record: the NCI reference comparison section and probability curves at the published horizons 2026-12-01 18:32:11 -06:00
Angel Capetillo Zavala 8fc06038fb CaCu record: stages with states and sources, segmented risk scales, antecedents and collapsible findings 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala e1e8da6093 CaCu indicators: one selector for the cytology and HPV genotype views, grouped bars and genotype labels 2026-12-01 17:15:17 -06:00
Angel Capetillo Zavala 81894a3777 CaCu: show screening rounds and restore category palettes 2026-12-01 14:22:23 -06:00
51 changed files with 6923 additions and 383 deletions
+276 -2
View File
@@ -1,10 +1,23 @@
import { expect, test } from '@playwright/test';
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
test.beforeEach(async ({ page }) => {
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
});
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 TITLES = {
cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Valor predictivo positivo de la colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia',
};
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page,
}) => {
@@ -23,7 +36,6 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
@@ -34,7 +46,64 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
// one selector for the cytology distribution and the HPV by genotype; the biopsy card is apart
await expect(
tab.locator('app-readings', {
has: page.getByRole('heading', { name: 'Pacientes evaluadas por resultado de VPH' }),
}),
).toHaveCount(0);
const views = tab.getByRole('radiogroup', { name: VIEWS_LABEL });
await expect(views.getByRole('radio')).toHaveText(VIEWS);
await expect(views.getByRole('radio', { name: 'General' })).toBeChecked();
await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
for (const view of VIEWS.slice(1)) {
await views.getByRole('radio', { name: view }).click();
for (const card of [TITLES.cytology, TITLES.genotype]) {
const readings = tab.locator('app-readings', {
has: page.getByRole('heading', { name: card }),
});
// each card has no toggle of its own: the selector drives both
await expect(readings.getByRole('radio')).toHaveCount(0);
// no long description beside the bars: the cards read from their title, note and legend
await expect(readings).not.toContainText(
/Cada barra|Cada paciente cuenta una vez|«Detección inicial»|una barra vacía|«Positivo»/,
);
await expect(
readings
.locator('.group')
.first()
.or(readings.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
}
}
const biopsyCard = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.biopsy }),
});
await expect(biopsyCard.getByRole('radio')).toHaveCount(0);
await views.getByRole('radio', { name: 'General' }).click();
await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: TITLES.cytology }) })
.getByRole('table'),
).toBeVisible();
// the PPV cards keep their round tab, in the same words and order
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.colposcopy }),
});
await colposcopy.getByRole('radio', ROUND).click();
await expect(
colposcopy
.getByRole('table', ROUND)
.or(colposcopy.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.ppvBiopsy }),
})
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible();
@@ -67,3 +136,208 @@ test('riesgos cacu: ages filter the whole list and a row opens its stages', asyn
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried on top of the API's own answers. They show how the page draws them, not the
// backend. The shared selector drives the cytology and the HPV-by-genotype cards; the PPV cards keep a tab.
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
const GENOTYPE_COLOURS = {
Negativo: '#42A77E',
'VPH 16': '#DF8640',
'VPH 18': '#C29C42',
'VPH 16 y 18': '#C24269',
Positivo: '#A8C243',
};
const CYTOLOGY_COLOURS = {
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const view = async (name: string) => {
await tab.getByRole('radiogroup', { name: VIEWS_LABEL }).getByRole('radio', { name }).click();
};
/** A PPV card on its round tab. */
const ppv = async (key: 'colposcopy' | 'ppvBiopsy') => {
await tab
.getByRole('radio', { name: key === 'colposcopy' ? 'Colposcopía' : 'Biopsia', exact: true })
.click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, card, view, ppv };
}
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first();
/** The groups of a card as the page draws them: "label<br>n = N", the width of the first bar and the colour of
* each category (the first group's rows), in hex. */
const traces = (readings: Locator) =>
readings.evaluate((el) => {
const hex = (rgb: string) =>
'#' +
(rgb.match(/\d+/g) ?? [])
.slice(0, 3)
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const groups = [...el.querySelectorAll('.group')];
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>n = ${g.querySelector('.n')!.textContent!.replace('n = ', '').trim()}`,
),
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries(
[...groups[0].querySelectorAll('.row')].map((r) => [
r.querySelector('.name')!.textContent!.trim(),
hex(getComputedStyle(r.querySelector('.fill')!).backgroundColor),
]),
),
};
});
for (const key of ['colposcopy', 'ppvBiopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'as-is');
const readings = await ppv(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'no-initial');
const readings = await ppv(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'unpublished');
const readings = await ppv(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
for (const card of ['cytology', 'genotype'] as const) {
test(`rondas (simulado) ${card}: the selector draws the rounds in order, with the category colours`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'as-is');
await view(ROUND.name);
const readings = of(TITLES[card]);
await expect(plotOf(readings)).toBeVisible();
const found = await traces(readings);
expect(found.y.map((l) => l.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(found.colours).toMatchObject(card === 'cytology' ? CYTOLOGY_COLOURS : GENOTYPE_COLOURS);
});
test(`rondas (simulado) ${card}: an empty initial group is an empty bar with its zero`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name);
const found = await traces(of(TITLES[card]));
expect(found.y[0]).toBe('Detección inicial<br>n = 0');
expect(found.x[0]).toBe(0);
});
test(`rondas (simulado) ${card}: without the stratum the selector says it is not available`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'unpublished');
await view(ROUND.name);
await expect(of(TITLES[card])).toContainText('No disponible');
});
}
test('rondas (simulado): the genotype card never shows the incomplete positives, and carries no long description', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).not.toContainText('«Positivo»');
await expect(readings).not.toContainText('Cada barra');
await expect(readings.getByRole('rowheader')).not.toContainText([
'Otro de alto riesgo',
'incompleto',
]);
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim())).toEqual([
'Negativo',
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
const found = await traces(readings);
expect(Object.keys(found.colours)).toEqual(Object.keys(GENOTYPE_COLOURS));
}
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the shared selector on each view lays out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { view, ppv } = await withRounds(page, 'as-is');
for (const name of VIEWS) {
await view(name);
await page.waitForTimeout(1200);
// every option of the selector is inside the window (it wraps on a narrow screen)
for (const box of await page
.getByRole('radiogroup', { name: VIEWS_LABEL })
.getByRole('radio')
.evaluateAll((els) =>
els.map((e) => e.closest('mat-button-toggle')!.getBoundingClientRect().right),
))
expect(box).toBeLessThanOrEqual(width);
expect(await layoutProblems(page), name).toEqual([]);
}
await ppv('colposcopy');
await ppv('ppvBiopsy');
await page.waitForTimeout(1200);
expect(await layoutProblems(page)).toEqual([]);
});
}
File diff suppressed because it is too large Load Diff
+88
View File
@@ -0,0 +1,88 @@
import type { Page } from '@playwright/test';
/** SIMULATED answers. The pages read the API's aggregated MeasureReports; these helpers pass them
* through the browser and rewrite the screening-round strata, so the cards can be tried with the
* groups the contract of `rebuild` allows (stratum `round`, crossed `round-category`) without
* loading data. They prove how the page draws such answers, not what the backend computes.
*
* - `as-is`: the answers untouched, with a stratum named `screening_round` renamed `round`.
* - `no-initial`: nobody is in the initial group (the group is absent and the totals drop).
* - `unclassified`: the initial group folds into "Sin dato" (what 5740's answers look like).
* - `unpublished`: the round strata are not in the answers. */
export type Simulation = 'as-is' | 'no-initial' | 'unclassified' | 'unpublished';
type Stratum = {
value?: { text?: string };
component?: { value?: { text?: string } }[];
population?: { code?: { coding?: { code?: string }[] }; count: number }[];
};
type Stratifier = { code?: { coding?: { code?: string }[] }[]; stratum?: Stratum[] };
const named = (s: Stratifier) => (s.code ?? []).map((c) => c.coding?.[0]?.code).join('-');
const label = (x: Stratum) => x.component?.[0]?.value?.text ?? x.value?.text;
const pop = (o: { population?: Stratum['population'] }, code: string) =>
o.population?.find((p) => p.code?.coding?.[0]?.code === code);
function fold(into: Stratum, from: Stratum) {
for (const p of from.population ?? []) {
const q = pop(into, p.code!.coding![0].code!);
if (q) q.count += p.count;
else (into.population ??= []).push(structuredClone(p));
}
}
export function simulate(report: any, how: Simulation) {
const group = report?.group?.[0];
if (!group) return report;
for (const s of group.stratifier ?? ([] as Stratifier[]))
for (const c of s.code ?? []) {
const k = c.coding?.[0];
if (k?.code === 'screening_round') k.code = 'round';
}
const rounds: Stratifier[] = (group.stratifier ?? []).filter((s: Stratifier) =>
['round', 'round-category'].includes(named(s)),
);
if (how === 'unpublished')
group.stratifier = (group.stratifier ?? []).filter((s: Stratifier) => !rounds.includes(s));
if (how === 'no-initial' || how === 'unclassified')
for (const s of rounds) {
const initial = (s.stratum ?? []).filter((x) => label(x) === 'initial');
const rest = (s.stratum ?? []).filter((x) => label(x) !== 'initial');
for (const x of initial) {
if (how === 'unclassified') {
const other = x.component?.[1]?.value?.text;
const target = rest.find(
(y) => label(y) === 'no_data' && (!other || y.component?.[1]?.value?.text === other),
);
if (target) fold(target, x);
else {
(x.component ? x.component[0].value! : x.value!).text = 'no_data';
rest.push(x);
}
} else if (named(s) === 'round') {
// the group vanishes and the period's total drops by its patients: a real zero
for (const p of x.population ?? []) {
const total = pop(group, p.code!.coding![0].code!);
if (total && p.code!.coding![0].code !== 'numerator')
total.count = Math.max(0, total.count - p.count);
}
}
}
s.stratum = rest;
}
return report;
}
/** Answers every CaCu MeasureReport search through `simulate`. */
export async function simulateRounds(page: Page, how: Simulation) {
await page.route('**/api/cacu/fhir/MeasureReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const entry of body.entry ?? []) simulate(entry.resource, how);
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
+285
View File
@@ -292,6 +292,7 @@
"default": "identity",
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -443,6 +444,7 @@
"description": "Qu\u00e9 estudio se saca del documento.",
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -465,6 +467,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -641,6 +647,7 @@
"entity": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -663,6 +670,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -1530,6 +1541,7 @@
"entity": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -2117,6 +2129,7 @@
"description": "En qu\u00e9 estudio de la plataforma se guarda.",
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -2139,6 +2152,10 @@
"label": "Identidad de la persona",
"value": "identity"
},
{
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
"value": "cacu_eligibility_evidence"
},
{
"label": "Citolog\u00eda cervical",
"value": "cervical_cytology"
@@ -4056,6 +4073,7 @@
"schema": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -4164,6 +4182,7 @@
"schema": {
"enum": [
"identity",
"cacu_eligibility_evidence",
"cervical_cytology",
"cervical_biopsy",
"mammography",
@@ -5907,6 +5926,272 @@
]
}
},
"/{domain}/fhir/Patient/{id}/$eligibility": {
"get": {
"description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.",
"operationId": "cacu_eligibility",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Limit the report to one CaCu scenario",
"in": "query",
"name": "scenario",
"required": false,
"schema": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"description": "Limit the report to one CaCu scenario",
"title": "Scenario"
}
},
{
"description": "Only index dates up to this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only index dates up to this day",
"title": "Cutoff"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Eligibility",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$reference-risk": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.",
"operationId": "reference_risk",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Reference Risk",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Patient/{id}/$risk-series": {
"get": {
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.",
"operationId": "cacu_risk_series",
"parameters": [
{
"in": "path",
"name": "domain",
"required": true,
"schema": {
"$ref": "#/components/schemas/Domain"
}
},
{
"in": "path",
"name": "id",
"required": true,
"schema": {
"title": "Id",
"type": "string"
}
},
{
"description": "Only what was reported by this day",
"in": "query",
"name": "cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "Only what was reported by this day",
"title": "Cutoff"
}
},
{
"description": "The cytology's sample day",
"in": "query",
"name": "sample",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"description": "The cytology's sample day",
"title": "Sample"
}
}
],
"responses": {
"200": {
"content": {
"application/fhir+json": {
"schema": {
"type": "object"
}
}
},
"description": "FHIR"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Cacu Risk Series",
"tags": [
"fhir"
]
}
},
"/{domain}/fhir/Procedure": {
"get": {
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuEligibility$Params {
domain: Domain;
id: string;
/**
* Limit the report to one CaCu scenario
*/
scenario?: (string | null);
/**
* Only index dates up to this day
*/
cutoff?: (string | null);
}
export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('scenario', params.scenario, {});
rb.query('cutoff', params.cutoff, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface CacuRiskSeries$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
+48
View File
@@ -0,0 +1,48 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { StrictHttpResponse } from '../../strict-http-response';
import { RequestBuilder } from '../../request-builder';
import { Domain } from '../../models/domain';
export interface ReferenceRisk$Params {
domain: Domain;
id: string;
/**
* Only what was reported by this day
*/
cutoff?: (string | null);
/**
* The cytology's sample day
*/
sample?: (string | null);
}
export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
}>> {
const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
if (params) {
rb.path('domain', params.domain, {});
rb.path('id', params.id, {});
rb.query('cutoff', params.cutoff, {});
rb.query('sample', params.sample, {});
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<{
}>;
})
);
}
referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Conflicts$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+1 -1
View File
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
export interface Held$Params {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
}
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
+6
View File
@@ -113,6 +113,12 @@ export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/sea
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
export { readPatient as readPatient } from './fn/fhir/read-patient';
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
export type { ReferenceRisk$Params as ReferenceRisk$Params } from './fn/fhir/reference-risk';
export { referenceRisk as referenceRisk } from './fn/fhir/reference-risk';
export type { CacuRiskSeries$Params as CacuRiskSeries$Params } from './fn/fhir/cacu-risk-series';
export { cacuRiskSeries as cacuRiskSeries } from './fn/fhir/cacu-risk-series';
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
+1 -1
View File
@@ -7,7 +7,7 @@
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
*/
export interface Correction {
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
field: string;
record: string;
value: string;
+1 -1
View File
@@ -25,7 +25,7 @@ export interface Extract {
/**
* Qué estudio se saca del documento.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
formats?: {
[key: string]: string;
};
+1 -1
View File
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
export interface Fhir {
column?: string;
concept_map?: (string | null);
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'fhir';
+1 -1
View File
@@ -2,7 +2,7 @@
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Rejection {
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
reason: string;
record: string;
}
+1 -1
View File
@@ -12,7 +12,7 @@ export interface Target {
/**
* En qué estudio de la plataforma se guarda.
*/
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
id: string;
inputs?: Array<string>;
kind?: 'target';
+53 -19
View File
@@ -10,23 +10,44 @@ interface Band {
high?: (number | null)[];
}
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The stretches of x where the curve has both limits: a band is drawn only there, never from a
* limit that is absent (an absent limit is not zero). */
function bandRuns(b: Band): number[][] {
const runs: number[][] = [];
let run: number[] = [];
b.x.forEach((x, i) => {
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
else {
if (run.length > 1) runs.push(run);
run = [];
}
});
if (run.length > 1) runs.push(run);
return runs;
}
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
lines.push({
x: [...b.x, ...[...b.x].reverse()],
y: [...b.high, ...[...b.low].reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
for (const run of bandRuns(b)) {
const x = run.map((i) => b.x[i]);
lines.push({
x: [...x, ...[...x].reverse()],
y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
}
}
lines.push({
x: b.x,
y: b.y,
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name,
type: 'scatter',
mode: 'lines',
@@ -295,20 +316,33 @@ export function scenarioFigure(
};
}
/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
* point without both limits has no bar. */
function points(
name: string,
x: number[],
p: { S: number[]; low: number[]; high: number[] },
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> {
const errors = p.S.map((value, i) => {
const low = p.low?.[i];
const high = p.high?.[i];
return finite(value) && finite(low) && finite(high)
? { up: high - value, down: value - low }
: null;
});
return {
x,
y: p.S,
error_y: {
type: 'data',
symmetric: false,
array: p.high.map((h, i) => h - p.S[i]),
arrayminus: p.S.map((v, i) => v - p.low[i]),
},
y: p.S.map((v) => (finite(v) ? v : null)) as number[],
...(errors.some((error) => error !== null)
? {
error_y: {
type: 'data' as const,
symmetric: false,
array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: errors.map((error) => error?.down ?? null) as number[],
},
}
: {}),
name,
type: 'scatter',
mode: 'markers',
+304 -1
View File
@@ -1,4 +1,5 @@
import { bars } from './bars';
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { scenarioBars } from './figures';
import { Reading } from './measures';
describe('bars', () => {
@@ -24,6 +25,308 @@ describe('bars', () => {
const mode = { kind: 'shares', label: 'x', measure: 'M', stratum: 's', order: ['initial'] };
expect(bars(mode as any, () => r)!.rows[0].cells).toEqual(['0/0', '—']);
});
describe('screening rounds (complete)', () => {
const ORDER = ['initial', 'subsequent', 'no_data'];
const cell = (numerator: number, denominator: number) => ({ numerator, denominator });
const ppv = (strata: Record<string, any>, total: number): Reading => ({
populations: { 'initial-population': total, denominator: total },
strata: { round: strata },
});
const mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
} as const;
it('lists the three groups in order with their own counts', () => {
const r = ppv({ no_data: cell(1, 4), subsequent: cell(6, 10), initial: cell(0, 6) }, 20);
const t = bars(mode, () => r)!;
expect(t.rows.map((x) => x.label)).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(t.rows.map((x) => x.cells)).toEqual([
['0/6', '0.0 %'],
['6/10', '60.0 %'],
['1/4', '25.0 %'],
]);
expect(t.note).toBeUndefined();
});
it('a group the report leaves out is zero patients when the counts add up', () => {
const r = ppv({ no_data: cell(0, 3), subsequent: cell(6, 10) }, 13);
const initial = bars(mode, () => r)!.rows[0];
expect(initial.cells).toEqual(['0/0', '—']);
expect(initial.hint).toBe('Sin pacientes en el periodo');
});
it('a group left out is not available when the counts do not add up', () => {
const r = ppv({ subsequent: cell(6, 10) }, 13);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['—', '—']);
expect(t.rows[0].hint).toBe('No disponible');
expect(t.note).toContain('no concilian');
});
it('a zero numerator over a positive denominator is 0 %, a zero denominator has no rate', () => {
const r = ppv({ initial: cell(0, 5), subsequent: cell(0, 0), no_data: cell(2, 3) }, 8);
const t = bars(mode, () => r)!;
expect(t.rows[0].cells).toEqual(['0/5', '0.0 %']);
expect(t.rows[1].cells).toEqual(['0/0', '—']);
expect(t.rows[1].hint).toBe('Sin pacientes en el periodo');
});
it('warns when only "Sin dato" holds patients', () => {
const r = ppv({ no_data: cell(3, 7) }, 7);
const t = bars(mode, () => r)!;
expect(t.rows[2].cells).toEqual(['3/7', '42.9 %']);
expect(t.note).toContain('información no registrada');
});
it('draws nothing without patients and says "No disponible" without the stratifier', () => {
expect(bars(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 0))).toBeUndefined();
expect(unavailable(mode, () => ppv({}, 9))).toContain('No disponible');
expect(bars(mode, () => ppv({}, 9))).toBeUndefined();
});
it('a cell that is not whole or has a numerator above its denominator is not available', () => {
const r = ppv({ initial: cell(5, 3), subsequent: cell(1, 2), no_data: cell(0, 1) }, 6);
expect(bars(mode, () => r)!.rows[0].hint).toBe('No disponible');
});
it('VPH positives: groups from the crossed cells, absent ones reconciled', () => {
const r: Reading = {
populations: { 'initial-population': 12 },
strata: {
'round-category': {
'subsequent|positive': { 'initial-population': 3 },
'subsequent|negative': { 'initial-population': 7 },
'no_data|negative': { 'initial-population': 2 },
},
},
};
const t = bars(
{
kind: 'positives',
label: 'x',
measure: 'M',
stratum: 'round',
order: ORDER,
complete: true,
},
() => r,
)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['0/0', '—'],
['3/10', '30.0 %'],
['0/2', '0.0 %'],
]);
});
});
describe('cytology by round', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#0a0', group: '' },
{ code: 'HSIL', label: 'LIEAG', color: '#a00', group: '' },
];
const reading = (cells: Record<string, number>, total: number): Reading => ({
populations: { 'initial-population': total },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const draw = (r: Reading) =>
scenarioBars(
r,
{ groups: [], categories: cats },
'round',
(c) =>
c === 'initial'
? 'Detección inicial'
: c === 'subsequent'
? 'Detección subsecuente'
: 'Sin dato',
['initial', 'subsequent', 'no_data'],
{ fill: true },
);
it('keeps the order and shows each bar with its n, an empty one included', () => {
const f = draw(
reading({ 'subsequent|NILM': 6, 'subsequent|HSIL': 2, 'no_data|NILM': 2 }, 10),
);
const y = (f.data[0] as any).y;
expect(y).toEqual([
'Detección inicial<br>n = 0',
'Detección subsecuente<br>n = 8',
'Sin dato<br>n = 2',
]);
expect((f.data[0] as any).x).toEqual([0, 75, 100]);
});
it('leaves out a group that does not reconcile', () => {
const f = draw(reading({ 'subsequent|NILM': 6 }, 10));
expect((f.data[0] as any).y).toEqual(['Detección subsecuente<br>n = 6']);
});
});
});
describe('shared views of cytology and HPV by genotype', () => {
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#42A77E', group: '' },
{ code: 'positive_other', label: 'Positivo', color: '#A8C243', group: '' },
];
const reading = (cells: Record<string, number>): Reading => ({
populations: { 'initial-population': Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
category: {
negative: { 'initial-population': 5 },
positive_other: { 'initial-population': 2 },
positive_incomplete: { 'initial-population': 3 },
},
'age_group-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
const counts: Mode = {
kind: 'counts',
label: 'General',
measure: 'M',
catalog: HPV,
hidden: { codes: ['positive_incomplete', 'inconsistent'], unit: 'reportes' },
};
it('does not list a hidden category but keeps it in the total and the percentages', () => {
const t = bars(counts, () => reading({}))!;
expect(t.rows.map((x) => x.label)).toEqual(['Negativo', 'Positivo']);
expect(t.rows.map((x) => x.cells)).toEqual([
['5', '50.0 %'],
['2', '20.0 %'],
]); // of 10 reports
expect(t.note).toBe(
'3 reportes (Positivo con genotipificación incompleta) no se muestran desglosados; están incluidos en el total y en los porcentajes.',
);
});
it('says nothing when no report is hidden', () => {
const r: Reading = {
populations: {},
strata: { category: { negative: { 'initial-population': 1 } } },
};
expect(hiddenNote(counts, () => r)).toBeUndefined();
});
it('a figure by groups is not available without its breakdown, and counts every record of the group on request', () => {
const mode = {
kind: 'figure',
label: 'Por grupo de edad',
measure: 'M',
figure: 'scenarios',
stratum: 'age_group',
catalog: HPV,
} as const;
const noBreakdown: Reading = {
populations: { 'initial-population': 4 },
strata: { category: {} },
};
expect(unavailable(mode, () => noBreakdown)).toBe(
'No disponible: el informe de este periodo no publica el desglose «Por grupo de edad».',
);
const r: Reading = {
populations: { 'initial-population': 10 },
strata: {
'age_group-category': {
'25-34|negative': { 'initial-population': 4 },
'25-34|positive_other': { 'initial-population': 1 },
'25-34|positive_incomplete': { 'initial-population': 5 },
},
},
};
const label = (c: string) => c;
const own = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34']);
const all = scenarioBars(r, { groups: [], categories: HPV }, 'age_group', label, ['25-34'], {
ofAll: true,
});
expect((own.data[0] as any).x).toEqual([80]); // 4 of the 5 the catalog draws
expect((all.data[0] as any).x).toEqual([40]); // 4 of the group's 10 reports
expect((all.data[0] as any).y).toEqual(['25-34<br>n = 10']);
});
});
describe('independent bars by group', () => {
const cats = [
{ code: 'NILM', label: 'Normal', color: '#408651' },
{ code: 'HSIL', label: 'LIEAG', color: '#CE4778' },
];
const mode = (more: object = {}): Mode =>
({
kind: 'grouped',
label: 'x',
measure: 'M',
catalog: cats,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
unit: 'pacientes',
...more,
}) as Mode;
const reading = (cells: Record<string, number>, total?: number): Reading => ({
populations: { 'initial-population': total ?? Object.values(cells).reduce((a, b) => a + b, 0) },
strata: {
'round-category': Object.fromEntries(
Object.entries(cells).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
it('draws one bar per category in each group: count, denominator and percent over its own records', () => {
const g = grouped(mode(), () =>
reading({ 'initial|NILM': 3, 'initial|HSIL': 1, 'subsequent|NILM': 6 }),
)!;
expect(g.groups.map((x) => [x.label, x.total])).toEqual([
['Detección inicial', 4],
['Detección subsecuente', 6],
]);
expect(g.groups[0].rows.map((r) => [r.label, r.text, r.percent, r.color])).toEqual([
['Normal', '3/4 · 75.0 %', 75, '#408651'],
['LIEAG', '1/4 · 25.0 %', 25, '#CE4778'],
]);
expect(g.groups[1].rows.map((r) => r.text)).toEqual(['6/6 · 100.0 %', '0/6 · 0.0 %']); // a zero numerator is 0 %
});
it('an empty group has no percent; with complete it is drawn only when the counts reconcile', () => {
const empty = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2, 'no_data|HSIL': 1 }),
)!;
expect(empty.groups.map((x) => x.code)).toEqual(['initial', 'subsequent', 'no_data']);
expect(empty.groups[0]).toMatchObject({ total: 0, hint: 'Sin pacientes en el grupo' });
expect(empty.groups[0].rows.map((r) => [r.text, r.percent])).toEqual([
['0/0 · —', undefined],
['0/0 · —', undefined],
]);
expect(empty.note).toContain('una categoría en cero significa');
const unreconciled = grouped(mode({ complete: true }), () =>
reading({ 'subsequent|NILM': 2 }, 5),
)!;
expect(unreconciled.groups.map((x) => x.code)).toEqual(['subsequent']);
expect(unreconciled.note).toContain('no concilian');
const open = grouped(mode(), () => reading({ 'subsequent|NILM': 2 }))!;
expect(open.groups.map((x) => x.code)).toEqual(['subsequent']); // without complete: only the listed groups
});
it('each group may count all its records, hidden categories included', () => {
const r = reading({ 'initial|NILM': 2, 'initial|positive_incomplete': 2 });
const own = grouped(mode(), () => r)!;
const all = grouped(mode({ ofAll: true }), () => r)!;
expect(own.groups[0].total).toBe(2);
expect(all.groups[0].total).toBe(4);
expect(all.groups[0].rows[0].text).toBe('2/4 · 50.0 %');
});
it('is not available without the breakdown, and draws nothing without records', () => {
const none: Reading = { populations: { 'initial-population': 4 }, strata: {} };
expect(grouped(mode(), () => none)).toBeUndefined();
expect(unavailable(mode(), () => none)).toContain('No disponible');
expect(grouped(mode(), () => reading({}, 0))).toBeUndefined();
});
it('says that unclassified records leave a classified group empty, and warns when none is classified', () => {
const lone = grouped(mode({ complete: true }), () => reading({ 'no_data|NILM': 3 }))!;
expect(lone.note).toContain('información no registrada');
});
it('a proportion split into its parts shows both in units and shares', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const t = bars({ kind: 'split', label: 'x', measure: 'M', yes: 'Con', no: 'Sin' }, () => r)!;
+351 -43
View File
@@ -1,4 +1,5 @@
import { CIE10 } from './cie10';
import { NEUTRAL_DARK } from './cacu-palette';
import { name, Reading } from './measures';
/** A category as drawn: its code in the report, its name and its colour. */
@@ -10,33 +11,119 @@ export type Mode = {
caption?: string;
/** said above the table: what its rows count (patients, reported biopsies…) */
heading?: string;
} &
/** `percent`: every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
(
| { kind: 'counts'; measure: string; catalog: Category[]; percent?: boolean }
| { kind: 'shares'; measure: string; stratum: string; order: string[] }
| { kind: 'positives'; measure: string; stratum: string; order: string[] }
| { kind: 'signs'; measure: string; strata: string[] }
| { kind: 'days'; steps: { label: string; measure: string }[] }
| { kind: 'days-by'; measure: string; stratum: string }
/** 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] }
/** Each row's units by result (a bar in segments), and the share of the row's units with a
* result that are `malignant`; a row with units and no result is not a row with none */
| {
kind: 'outcomes';
measure: string;
stratum: string;
rows: Category[];
results: Category[];
malignant: string[];
}
| { kind: 'figure'; measure: string; figure: 'donut' | 'scenarios'; catalog?: Category[] }
);
} & (
| {
kind: 'counts';
measure: string;
catalog: Category[];
hidden?: Hidden;
/** every bar on a fixed scale of 0 to 100 %, so its length is the share shown */
percent?: boolean;
}
| {
kind: 'shares';
measure: string;
stratum: string;
order: string[];
complete?: boolean;
colors?: Colors;
}
| {
kind: 'positives';
measure: string;
stratum: string;
order: string[];
complete?: boolean;
colors?: Colors;
}
| { kind: 'signs'; measure: string; strata: string[]; colors?: Colors }
| {
kind: 'grouped';
measure: string;
/** the categories drawn in each group, in this order (each in its own colour) */
catalog: Category[];
/** the groups' stratifier (its crossed cells `<stratum>-category`) and their order */
stratum: string;
order: string[];
/** what the records are called ("pacientes", "reportes") */
unit: string;
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
complete?: boolean;
/** each group's denominator is all its records, not only those of the catalog's categories */
ofAll?: boolean;
hidden?: Hidden;
}
| { kind: 'days'; steps: { label: string; measure: 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 */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
/** Each row's units by result (a bar in segments), and the share of the row's units with a
* result that are `malignant`; a row with units and no result is not a row with none */
| {
kind: 'outcomes';
measure: string;
stratum: string;
rows: Category[];
results: Category[];
malignant: string[];
}
| {
kind: 'figure';
measure: string;
figure: 'donut' | 'scenarios';
/** a donut's colour by part (a category, or numerator and rest); none: the page's palette */
colors?: Colors;
catalog?: Category[];
/** the stratifier a scenarios figure crosses with the category (default: the follow-up status) */
stratum?: string;
order?: string[];
/** draw the groups of `order` the report leaves out as zero (see `reconciles`) */
complete?: boolean;
/** each bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
hidden?: Hidden;
}
);
/** Categories a card does not draw: their records stay in the total and in the percentages. */
export type Hidden = { codes: string[]; unit: string };
/** A colour by category code (the category decides it, not its place in the report). */
export type Colors = Record<string, string>;
/** The colours of a median bar and of the marks of its quartiles. */
export type Tint = { bar: string; mark: string };
/** One category of a group as an independent bar of 0 to 100 %: its records over the group's. */
export interface GroupRow {
label: string;
color: string;
count: number;
/** the group's records (the denominator) */
of: number;
/** none when the group has no records: a rate over nothing is not drawn */
percent?: number;
/** "2/5 · 40.0 %"; "0/0 · —" for an empty group */
text: string;
}
export interface Group {
code: string;
label: string;
/** the group's records */
total: number;
/** why the group has no figures */
hint?: string;
rows: GroupRow[];
}
export interface Groups {
groups: Group[];
note?: string;
}
/** One bar: its length and quartile marks in % of the scale, and its cells of text. */
export interface Bar {
label: string;
/** why the row has no figures: no patients in the group, or not available */
hint?: string;
color?: string;
width: number;
marks: number[];
@@ -49,10 +136,67 @@ export interface Bar {
export interface Bars {
head: string[];
rows: Bar[];
/** the colour of the quartile marks, when the card has its own */
markColor?: string;
/** what the reader must know to take the rows right */
note?: string;
/** the colours of the segments */
legend?: { label: string; color: string }[];
}
export const NOT_AVAILABLE = 'No disponible';
export const NO_PATIENTS = 'Sin pacientes en el periodo';
const EMPTY_ROUND =
'Hay pacientes sin clasificación de ronda («Sin dato»): una categoría en cero significa que no hay pacientes clasificadas en esa ronda según la información disponible.';
const NO_ROUND =
'Ninguna paciente del periodo tiene clasificación de detección inicial o subsecuente: los grupos en cero reflejan información no registrada, no ausencia de pacientes.';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** A group the report does not list is zero patients only when the groups it lists add up to every
* patient of the period (the report leaves out empty groups); otherwise it is not available. */
export function reconciles(listed: number[], total: number): boolean {
return listed.every(whole) && whole(total) && listed.reduce((t, n) => t + n, 0) === total;
}
/** The patients of a reading: its cohort, or the denominator of a proportion. */
export const patients = (r?: Reading) =>
r?.populations['initial-population'] ?? r?.populations['denominator'] ?? 0;
/** Why a card of a "complete" mode, or a figure by groups, has nothing to draw though its period
* has records: the report does not publish the breakdown. Undefined when there is nothing to say. */
export function unavailable(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
const groups = mode.kind === 'grouped' || (mode.kind === 'figure' && mode.figure === 'scenarios');
const complete = 'complete' in mode && mode.complete;
if (!(groups || complete) || !('stratum' in mode) || !mode.stratum) return undefined;
const r = of(mode.measure);
if (!patients(r)) return undefined;
const key = mode.kind === 'shares' ? mode.stratum : `${mode.stratum}-category`;
return Object.keys(r?.strata[key] ?? {}).length
? undefined
: `${NOT_AVAILABLE}: el informe de este periodo no publica el desglose «${mode.label}».`;
}
/** What a card says about the categories it does not draw: how many records they hold and that
* they stay in the total and the percentages. Undefined when none is in the period. */
export function hiddenNote(
mode: Mode,
of: (measure: string) => Reading | undefined,
): string | undefined {
if (!('hidden' in mode) || !mode.hidden) return undefined;
const { codes, unit } = mode.hidden;
const cells = of(mode.measure)?.strata['category'] ?? {};
const found = codes.filter((c) => size(cells[c]));
if (!found.length) return undefined;
const n = found.reduce((t, c) => t + size(cells[c]), 0);
const names = found.map((c) => name(c)).join(', ');
const one = n === 1;
return `${n} ${one ? unit.replace(/s$/, '') : unit} (${names}) ${one ? 'no se muestra desglosado; está incluido' : 'no se muestran desglosados; están incluidos'} en el total y en los porcentajes.`;
}
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
@@ -65,11 +209,12 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
if (!total) return undefined;
// a category outside the catalog is listed after it, so the shares add up
const hidden = mode.hidden?.codes ?? [];
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c));
const rest = Object.keys(cells).filter((c) => !named.includes(c) && !hidden.includes(c));
const all = [
...mode.catalog,
...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
...mode.catalog.filter((c) => !hidden.includes(c.code)),
...rest.map((code) => ({ code, label: name(code), color: NEUTRAL_DARK })),
];
const most = mode.percent ? total : Math.max(...Object.values(cells).map(size));
return {
@@ -79,26 +224,67 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
note: hiddenNote(mode, of),
};
}
case 'shares': {
const cells = of(mode.measure)?.strata[mode.stratum] ?? {};
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]),
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
if (!mode.complete)
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [
name(c),
cells[c]['numerator'] ?? 0,
cells[c]['denominator'] ?? 0,
mode.colors?.[c],
]),
);
if (!patients(r) || !Object.keys(cells).length) return undefined;
const sound = (c: string) =>
whole(cells[c]?.['numerator']) &&
whole(cells[c]?.['denominator']) &&
cells[c]['numerator'] <= cells[c]['denominator'];
const ok = reconciles(
Object.keys(cells).map((c) => cells[c]['denominator']),
patients(r),
);
return complete(
mode.order,
Object.keys(cells),
ok,
(c) => (sound(c) ? [cells[c]['numerator'], cells[c]['denominator']] : undefined),
mode.colors,
);
}
case 'positives': {
const cells = of(mode.measure)?.strata[`${mode.stratum}-category`] ?? {};
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`])];
}),
if (!mode.complete)
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`]), mode.colors?.[c]];
}),
);
if (!patients(r) || !found.size) return undefined;
const ok = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
return complete(
mode.order,
[...found],
ok,
(c) => {
const positive = size(cells[`${c}|positive`]);
return [positive, positive + size(cells[`${c}|negative`])];
},
mode.colors,
);
}
case 'signs': {
@@ -108,7 +294,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative'])];
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}),
);
}
@@ -118,6 +304,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
mode.tint,
);
case 'days-by': {
const r = of(mode.measure);
@@ -130,6 +317,7 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
mode.tint,
);
}
case 'split': {
@@ -197,12 +385,127 @@ export function bars(mode: Mode, of: (measure: string) => Reading | undefined):
}
}
function ratios(rows: [string, number, number][]): Bars | undefined {
/** 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`). */
export function grouped(
mode: Mode,
of: (measure: string) => Reading | undefined,
): Groups | undefined {
if (mode.kind !== 'grouped') return undefined;
const r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
if (!patients(r) || !found.length) return undefined;
const n = (g: string, c: string) => size(cells[`${g}|${c}`]);
const reconciled = reconciles(
Object.values(cells).map((c) => c['initial-population']),
patients(r),
);
const codes = [
...mode.order.filter((g) => found.includes(g) || (mode.complete && reconciled)),
...found.filter((g) => !mode.order.includes(g)),
];
const total = (g: string) =>
mode.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === g)
.reduce((t, [, c]) => t + size(c), 0)
: mode.catalog.reduce((t, c) => t + n(g, c.code), 0);
const groups: Group[] = codes.map((code) => {
const den = total(code);
return {
code,
label: name(code),
total: den,
hint: den ? undefined : `Sin ${mode.unit} en el grupo`,
rows: mode.catalog.map((c) => {
const count = n(code, c.code);
const percent = den ? (100 * count) / den : undefined;
return {
label: c.label,
color: c.color,
count,
of: den,
percent,
text: `${count}/${den} · ${percent === undefined ? '—' : percent.toFixed(1) + ' %'}`,
};
}),
};
});
let note = hiddenNote(mode, of);
if (mode.complete) {
const unclassified = total('no_data');
const classified = groups.filter((g) => g.code !== 'no_data');
const none = classified.every((g) => !g.total);
const sentence = !reconciled
? 'Los conteos del informe no concilian con el total: los grupos ausentes no se muestran como cero.'
: none && unclassified
? NO_ROUND
: unclassified && classified.some((g) => !g.total)
? EMPTY_ROUND
: undefined;
note = [sentence, note].filter(Boolean).join(' ') || undefined;
}
return { groups, note };
}
/** Every group of a stratifier the card names, in its order: those the report lists with their
* counts; those it leaves out as no patients when the counts add up to the period's patients,
* else as not available. "Sin dato" keeps its own counts. */
function complete(
order: string[],
listed: string[],
reconciled: boolean,
counts: (code: string) => [number, number] | undefined,
colors: Colors = {},
): Bars {
const extra = listed.filter((c) => !order.includes(c));
const rows: Bar[] = [...order, ...extra].map((code) => {
const label = name(code);
const color = colors[code];
if (!listed.includes(code))
return reconciled
? { label, color, hint: NO_PATIENTS, width: 0, marks: [], cells: ['0/0', '—'] }
: { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const found = counts(code);
if (!found)
return { label, color, hint: NOT_AVAILABLE, width: 0, marks: [], cells: ['—', '—'] };
const [n, total] = found;
return {
label,
color,
hint: total ? undefined : NO_PATIENTS,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
};
});
const classified = order.filter((c) => c !== 'no_data' && listed.includes(c));
const empty = classified.filter((c) => !(counts(c)?.[1] ?? 0));
const none = empty.length === classified.length;
const unclassified = counts('no_data')?.[1] ?? 0;
return {
head: ['n/N', '%'],
rows,
note: !reconciled
? 'Los conteos del informe no concilian con el total de pacientes: los grupos ausentes no se muestran como cero.'
: none && listed.includes('no_data')
? NO_ROUND
: unclassified &&
(empty.length || order.some((c) => !listed.includes(c) && c !== 'no_data'))
? EMPTY_ROUND
: undefined,
};
}
function ratios(rows: [string, number, number, string?][]): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', '%'],
rows: rows.map(([label, n, total]) => ({
rows: rows.map(([label, n, total, color]) => ({
label,
color,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
@@ -211,17 +514,22 @@ function ratios(rows: [string, number, number][]): Bars | undefined {
}
type Score = { score?: number; low?: number; high?: number };
function medians(rows: { label: string; n: number; score?: Score }[]): Bars | undefined {
function medians(
rows: { label: string; n: number; score?: Score }[],
tint?: Tint,
): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
markColor: tint?.mark,
rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
color: tint?.bar,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
+76
View File
@@ -0,0 +1,76 @@
import { bars, Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
HPV_COLORS,
NEUTRAL,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
REQUEST_COLORS,
ROUND_COLORS,
STEEL,
} from './cacu-palette';
import type { Measure } from 'fhir/r4';
import { donut, Reading } from './measures';
const VPH = { negative: HPV_COLORS['negative'], positive: HPV_COLORS['positive_other'] };
describe('CaCu palette', () => {
it('a PPV group has the colour of its category elsewhere on the page', () => {
expect(PPV_CYTOLOGY_COLORS['ascus_plus']).toBe(CYTOLOGY_COLORS['ASC-US']);
expect(PPV_CYTOLOGY_COLORS['lsil_plus']).toBe(CYTOLOGY_COLORS['LSIL']);
expect(PPV_CYTOLOGY_COLORS['hsil_plus']).toBe(CYTOLOGY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['cin1_plus']).toBe(BIOPSY_COLORS['LSIL']);
expect(PPV_LEVEL_COLORS['cin2_plus']).toBe(BIOPSY_COLORS['HSIL']);
expect(PPV_LEVEL_COLORS['carcinoma']).toBe(BIOPSY_COLORS['carcinoma']);
expect(HPV_COLORS['hpv_16']).toBe(HPV_COLORS['positive_16']);
expect(HPV_COLORS['hpv_18']).toBe(HPV_COLORS['positive_18']);
expect(HPV_COLORS['positive']).toBe(HPV_COLORS['positive_other']);
expect(REQUEST_COLORS['high_grade']).toBe(CYTOLOGY_COLORS['HSIL']);
});
it('"Sin dato" and what is not classified are neutral everywhere', () => {
for (const colors of [
CYTOLOGY_COLORS,
HPV_COLORS,
BIOPSY_COLORS,
ROUND_COLORS,
PPV_CYTOLOGY_COLORS,
])
expect(colors['no_data']).toBe(NEUTRAL);
expect(REQUEST_COLORS['pending']).toBe(NEUTRAL);
expect(PPV_DONUT['rest']).toBe(NEUTRAL);
expect(ROUND_COLORS['initial']).toBe(STEEL);
});
it('a donut colours by category, not by place in the report', () => {
const measure = { scoring: { coding: [{ code: 'cohort' }] } } as unknown as Measure;
const cells = (order: string[]): Reading => ({
populations: {},
strata: { category: Object.fromEntries(order.map((c) => [c, { 'initial-population': 1 }])) },
});
const colours = (order: string[]) =>
(donut(measure, cells(order), 'category', VPH).data[0] as any).marker.colors;
expect(colours(['negative', 'positive'])).toEqual([VPH['negative'], VPH['positive']]);
expect(colours(['positive', 'negative'])).toEqual([VPH['positive'], VPH['negative']]);
});
it('bars take their colour from the mode by group, absent groups included', () => {
const r: Reading = {
populations: { 'initial-population': 5 },
strata: { round: { subsequent: { numerator: 1, denominator: 5 } } },
};
const mode: Mode = {
kind: 'shares',
label: 'x',
measure: 'M',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
complete: true,
colors: ROUND_COLORS,
};
expect(bars(mode, () => r)!.rows.map((x) => x.color)).toEqual([
ROUND_COLORS['initial'],
ROUND_COLORS['subsequent'],
ROUND_COLORS['no_data'],
]);
});
});
+88
View File
@@ -0,0 +1,88 @@
/** The colours of CaCu's charts, by category. A colour names a category (never a position in a
* report, never a threshold), so the same category looks the same on every card; neutral greys
* are for what is absent or not classified. They live here, not in the shared palette, so that no
* other domain (CaMa, TEA) takes them. */
/** Not classified, or no data. */
export const NEUTRAL = '#C9CDD2';
/** Not classified, a little darker: what a report names but a card does not. */
export const NEUTRAL_DARK = '#9AA3AB';
/** The steel tones of the groups that are not results: rounds, ages, follow-up status. */
export const STEEL = '#5F7F9A';
export const STEEL_MID = '#8FA7BB';
export const STEEL_LIGHT = '#B5C5D3';
/** Cytology by Bethesda category. */
export const CYTOLOGY_COLORS: Record<string, string> = {
NILM: '#408651',
'ASC-US': '#2778B8',
LSIL: '#B19525',
'ASC-H': '#7955B1',
HSIL: '#CE4778',
CIS: '#AA394D',
no_data: NEUTRAL,
};
/** HPV by genotype; `positive` (any high-risk type) is the colour of "positive other". */
export const HPV_COLORS: Record<string, string> = {
negative: '#42A77E',
positive_16: '#DF8640',
positive_18: '#C29C42',
positive_16_18: '#C24269',
positive_other: '#A8C243',
positive_incomplete: '#9C42C2',
inconsistent: '#687786',
positive: '#A8C243',
hpv_16: '#DF8640',
hpv_18: '#C29C42',
no_data: NEUTRAL,
};
/** Biopsy by the grade it states; the levels of a PPV (that grade or worse) take its colour. */
export const BIOPSY_COLORS: Record<string, string> = {
normal: '#408651',
LSIL: '#B19525',
HSIL: '#CE4778',
CIS: '#AA394D',
carcinoma: '#8D4C79',
cin1_plus: '#B19525',
cin2_plus: '#CE4778',
no_data: NEUTRAL,
};
/** What became of the biopsy requests: high grade is the colour of LIEAG, the rest steel. */
export const REQUEST_COLORS: Record<string, string> = {
high_grade: '#CE4778',
below_high_grade: STEEL_MID,
pending: NEUTRAL,
no_grade: NEUTRAL_DARK,
};
/** Detection round: steel tones; "Sin dato" is neutral. */
export const ROUND_COLORS: Record<string, string> = {
initial: STEEL,
subsequent: STEEL_MID,
no_data: NEUTRAL,
};
/** Referral PPV groups: cytology and histology levels by the colour of their category, HPV by
* genotype. */
export const PPV_CYTOLOGY_COLORS: Record<string, string> = {
ascus_plus: CYTOLOGY_COLORS['ASC-US'],
lsil_plus: CYTOLOGY_COLORS['LSIL'],
hsil_plus: CYTOLOGY_COLORS['HSIL'],
no_data: NEUTRAL,
};
export const PPV_LEVEL_COLORS: Record<string, string> = {
cin1_plus: BIOPSY_COLORS['LSIL'],
cin2_plus: BIOPSY_COLORS['HSIL'],
carcinoma: BIOPSY_COLORS['carcinoma'],
};
/** The whole of a PPV card as a donut: the colours of its two parts. */
export const PPV_DONUT: Record<string, string> = { numerator: '#6A8000', rest: NEUTRAL };
/** Median bars of the screening route, and the marks of their quartiles. */
export const DURATION = '#42A77E';
export const QUARTILE = '#17324D';
+35 -6
View File
@@ -1,4 +1,5 @@
import { type Figure, PALETTE } from '../plot';
import { reconciles } from './bars';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
@@ -96,14 +97,36 @@ export function scenarioBars(
catalog: Catalog,
stratum: string,
label: (code: string) => string,
/** the groups in this order (the ones the report lists, then any other) */
order?: string[],
options: {
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
fill?: boolean;
/** a bar is the share of all the group's records, not only of those the catalog draws */
ofAll?: boolean;
} = {},
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
const listed = Object.values(cells).map((c) => c['initial-population']);
const empty = reconciles(listed, r.populations['initial-population'] ?? 0);
const scenarios = order
? [
...order.filter((s) => found.includes(s) || (options.fill && empty)),
...found.filter((s) => !order.includes(s)),
]
: found.sort((a, b) => label(a).localeCompare(label(b), 'es'));
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
const totals = scenarios.map((s) =>
options.ofAll
? Object.entries(cells)
.filter(([k]) => k.split('|')[0] === s)
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0)
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
);
const y = order
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
: scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
@@ -118,7 +141,13 @@ export function scenarioBars(
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
title: {
text: order
? options.ofAll
? '% de los reportes del grupo'
: '% de pacientes con resultado'
: '% de pacientes del escenario con resultado',
},
ticksuffix: ' %',
range: [0, 100.5],
dtick: 20,
+3 -2
View File
@@ -13,6 +13,7 @@ export const LAYOUTS: Record<string, Layout> = {
'CACU_EU7',
'CACU_EU_TIEMPO_REPORTE',
'CACU_DIAS_TOMA_DIAGNOSTICO',
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
'CACU_DIAS_TOMA_TRATAMIENTO',
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
],
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
label: 'Diagnóstico tras biopsia',
step: 'Del resultado de biopsia al diagnóstico',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO',
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
+14 -5
View File
@@ -133,8 +133,8 @@ export const LABELS: Record<string, string> = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Inicial',
subsequent: 'Subsecuente',
initial: 'Detección inicial',
subsequent: 'Detección subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
@@ -146,6 +146,7 @@ export const LABELS: Record<string, string> = {
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
positive_incomplete: 'Positivo con genotipificación incompleta',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries(
@@ -202,15 +203,23 @@ export function detail(measure: Measure, r: Reading | undefined, unit = 'pacient
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure {
let labels: string[], values: number[];
export function donut(
measure: Measure,
r: Reading,
stratifier = 'category',
/** a colour by category code (a proportion: `numerator` and `rest`); a part without one takes the palette's */
colors?: Record<string, string>,
): Figure {
let labels: string[], values: number[], codes: string[];
if (scoring(measure) === 'proportion') {
const { numerator = 0, denominator = 0 } = r.populations;
labels = ['Numerador', 'Resto'];
codes = ['numerator', 'rest'];
values = [numerator, denominator - numerator];
} else {
const cells = Object.entries(r.strata[stratifier] ?? {});
labels = cells.map(([v]) => name(v));
codes = cells.map(([v]) => v);
values = cells.map(([, c]) => c['initial-population'] ?? 0);
}
return {
@@ -222,7 +231,7 @@ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Fi
values,
sort: false,
textinfo: 'value+percent',
marker: { colors: PALETTE },
marker: { colors: codes.map((c, i) => colors?.[c] ?? PALETTE[i % PALETTE.length]) },
},
],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
+124 -81
View File
@@ -1,4 +1,16 @@
import type { Mode } from './bars';
import {
BIOPSY_COLORS,
CYTOLOGY_COLORS,
DURATION,
HPV_COLORS,
PPV_CYTOLOGY_COLORS,
PPV_DONUT,
PPV_LEVEL_COLORS,
QUARTILE,
REQUEST_COLORS,
ROUND_COLORS,
} from './cacu-palette';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
@@ -11,12 +23,12 @@ const CYTOLOGY: Catalog = {
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' },
{ code: 'NILM', label: 'Normal', color: CYTOLOGY_COLORS['NILM'], group: 'normal' },
{ code: 'ASC-US', label: 'ASC-US', color: CYTOLOGY_COLORS['ASC-US'], group: 'abnormal' },
{ code: 'LSIL', label: 'LIEBG', color: CYTOLOGY_COLORS['LSIL'], group: 'abnormal' },
{ code: 'ASC-H', label: 'ASC-H', color: CYTOLOGY_COLORS['ASC-H'], group: 'abnormal' },
{ code: 'HSIL', label: 'LIEAG', color: CYTOLOGY_COLORS['HSIL'], group: 'abnormal' },
{ code: 'CIS', label: 'Carcinoma in situ', color: CYTOLOGY_COLORS['CIS'], group: 'abnormal' },
],
};
@@ -27,31 +39,78 @@ const BIOPSY: Catalog = {
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' },
{ code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' },
{ code: 'normal', label: 'Normal', color: BIOPSY_COLORS['normal'], group: 'low' },
{ code: 'LSIL', label: 'LIEBG (CIN 1)', color: BIOPSY_COLORS['LSIL'], group: 'low' },
{ code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: BIOPSY_COLORS['HSIL'], group: 'high' },
{ code: 'CIS', label: 'Carcinoma in situ', color: BIOPSY_COLORS['CIS'], group: 'high' },
{
code: 'carcinoma',
label: 'Carcinoma invasor',
color: BIOPSY_COLORS['carcinoma'],
group: 'high',
},
],
faded: ['normal', 'LSIL'],
};
/** HPV reports by genotype, and biopsy requests by what became of them. */
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#A8C243' },
{ code: 'positive_16', label: 'VPH 16', color: '#C24269' },
{ code: 'positive_18', label: 'VPH 18', color: '#9C42C2' },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' },
{ code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' },
{ code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' },
{ code: 'negative', label: 'Negativo', color: HPV_COLORS['negative'] },
{ code: 'positive_16', label: 'VPH 16', color: HPV_COLORS['positive_16'] },
{ code: 'positive_18', label: 'VPH 18', color: HPV_COLORS['positive_18'] },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: HPV_COLORS['positive_16_18'] },
{ code: 'positive_other', label: 'Positivo', color: HPV_COLORS['positive_other'] },
];
const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: '#C24269' },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' },
{ code: 'pending', label: 'Pendiente', color: '#C9CDD2' },
{ code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' },
{ code: 'high_grade', label: 'LIEAG o más', color: REQUEST_COLORS['high_grade'] },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: REQUEST_COLORS['below_high_grade'] },
{ code: 'pending', label: 'Pendiente', color: REQUEST_COLORS['pending'] },
{ code: 'no_grade', label: 'Sin grado', color: REQUEST_COLORS['no_grade'] },
];
/** The screening route's bars: a median, and the marks of its quartiles. */
const TINT = { bar: DURATION, mark: QUARTILE };
/** The screening rounds, in the order the cards draw them. */
const ROUNDS = ['initial', 'subsequent', 'no_data'];
const ROUND_CAPTION =
'Cada paciente está en un solo grupo, según su muestra (fecha de toma): detección inicial (primera vez en la vida), ' +
'subsecuente (detección previa registrada, o ya con colposcopía o tratamiento) o «Sin dato». ' +
'Un grupo sin pacientes se muestra en cero; sin porcentaje.';
/** 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'],
unit: 'reportes',
};
/** One measure's breakdowns by group, each as stacked bars of the categories of `catalog`. */
const groupViews = (
measure: string,
catalog: { code: string; label: string; color: string }[],
unit: string,
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {},
): 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,
...v,
...more,
}));
/** A PPV's card: the whole, and by each of its stratifiers. */
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
kind: 'readings',
@@ -59,13 +118,14 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut' },
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT },
{
kind: 'shares',
label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure,
stratum: 'cytology',
colors: PPV_CYTOLOGY_COLORS,
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
},
{
@@ -74,6 +134,7 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
caption: 'Los grupos se traslapan.',
measure,
stratum: 'hpv',
colors: HPV_COLORS,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
},
{
@@ -81,14 +142,18 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
label: 'Nivel de histología',
measure,
stratum: 'level',
colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
},
{
kind: 'shares',
label: 'Tamizaje',
label: 'Por detección inicial y subsecuente',
caption: ROUND_CAPTION,
measure,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
colors: ROUND_COLORS,
order: ROUNDS,
complete: true,
},
...more,
],
@@ -114,7 +179,12 @@ export const CACU: Page = {
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
title: 'Tiempo de tamizaje a primer diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
...CACU_DAYS,
},
{
@@ -136,16 +206,18 @@ export const CACU: Page = {
modes: [
{
kind: 'days',
tint: TINT,
label: 'Acumulado desde la toma',
steps: [
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
{ label: 'Diagnóstico tras biopsia', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA' },
],
},
{
kind: 'days',
tint: TINT,
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
@@ -156,11 +228,16 @@ export const CACU: Page = {
],
},
{
kind: 'days-by',
label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
stratum: 'diagnosis_code',
kind: 'days',
tint: TINT,
label: 'Primer diagnóstico',
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
},
{
kind: 'days',
tint: TINT,
label: 'Diagnóstico tras biopsia',
steps: [{ label: 'Toma a diagnóstico tras biopsia', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA' }],
},
],
},
@@ -169,32 +246,34 @@ 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],
sections: [
{
kind: 'readings',
follows: true,
title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
},
{
kind: 'figure',
label: 'Por escenario clínico',
measure: 'CACU_EU7',
figure: 'scenarios',
catalog: CYTOLOGY.categories,
},
{ kind: 'counts', label: GENERAL, measure: 'CACU_EU7', catalog: CYTOLOGY.categories },
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes'),
],
},
{
kind: 'readings',
follows: true,
title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.',
modes: [{ kind: 'counts', label: 'General', measure: 'CACU_VPH_GENOTIPO', catalog: HPV }],
modes: [
{
kind: 'counts',
label: GENERAL,
measure: 'CACU_VPH_GENOTIPO',
catalog: HPV,
hidden: HPV_HIDDEN,
},
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', { ofAll: true, hidden: HPV_HIDDEN }),
],
},
{
kind: 'readings',
@@ -211,42 +290,6 @@ export const CACU: Page = {
},
],
},
{
kind: 'readings',
title: 'Pacientes evaluadas por resultado de VPH',
headline: 'CACU_VPH',
note: 'Una vez cada paciente, por su última muestra con resultado.',
modes: [
{ kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' },
{
kind: 'positives',
label: 'Por grupo de edad',
measure: 'CACU_VPH',
stratum: 'age_group',
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
},
{
kind: 'positives',
label: 'Por estatus de seguimiento',
measure: 'CACU_VPH',
stratum: 'follow_up_status',
order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
},
{
kind: 'signs',
label: 'Por genotipo',
measure: 'CACU_VPH',
strata: ['hpv_16', 'hpv_18'],
},
{
kind: 'positives',
label: 'Por tamizaje',
measure: 'CACU_VPH',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
],
},
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
+16 -2
View File
@@ -30,6 +30,8 @@ export interface ReadingsCard {
unit?: string;
note?: string;
modes: Mode[];
/** in a `columns` section with `views`: takes the mode whose label the section's selector chose */
follows?: boolean;
}
export type Section =
| ReadingsCard
@@ -38,7 +40,14 @@ export type Section =
* medians); `step` reads each from the previous step. A reading with no steps is not offered. */
| { kind: 'route'; title: string; sample: RouteStep[]; step: RouteStep[] }
/** Cards side by side; the last one alone when odd. */
| { kind: 'columns'; title: string; sections: ReadingsCard[] }
| {
kind: 'columns';
title: string;
sections: ReadingsCard[];
/** one selector for the cards that `follow` it: the labels of their modes, the first by default */
views?: string[];
viewsLabel?: string;
}
/** One section at a time. */
/** `card`: the title, the tabs and the chosen reading in one card (the reading's own title is
* left out: its tab names it) */
@@ -472,10 +481,15 @@ export const HISTORY: Record<string, History> = {
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico',
title: 'Tiempo de tamizaje a primer diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a diagnóstico tras biopsia',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
kind: 'median',
},
{
title: 'Tiempo de tamizaje a tratamiento',
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
+163 -5
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, Mode } from './bars';
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars. */
@@ -20,7 +20,7 @@ import { Reading } from './measures';
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1) {
@if (modes().length > 1 && !view()) {
<mat-button-toggle-group
[attr.aria-label]="title()"
[value]="mode().label"
@@ -39,8 +39,49 @@ import { Reading } from './measures';
}
@if (loading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (missing(); as why) {
<p class="state" role="status">{{ why }}</p>
} @else if (groups(); as g) {
<div class="axis" aria-hidden="true">
<span></span>
<span class="ticks">
<span style="left: 0">0 %</span><span style="left: 25%">25 %</span
><span style="left: 50%">50 %</span><span style="left: 75%">75 %</span
><span style="left: 100%">100 %</span>
</span>
<span></span>
</div>
@for (group of g.groups; track group.code) {
<section class="group" [attr.data-group]="group.code" [attr.aria-label]="group.label">
<h4>
{{ group.label }} <span class="n">n = {{ group.total }}</span>
@if (group.hint) {
<span class="hint">{{ group.hint }}</span>
}
</h4>
@for (row of group.rows; track row.label) {
<div class="row" [attr.data-category]="row.label">
<span class="name">{{ row.label }}</span>
<span class="track" aria-hidden="true">
<span
class="fill"
[style.width.%]="row.percent ?? 0"
[style.background]="row.color"
></span>
</span>
<span class="value">{{ row.text }}</span>
</div>
}
</section>
}
@if (g.note) {
<p class="state">{{ g.note }}</p>
}
} @else if (figure(); as f) {
<app-plot [figure]="f" [height]="300" />
<app-plot [figure]="f" [height]="height()" />
@if (hidden(); as why) {
<p class="state">{{ why }}</p>
}
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
@@ -56,6 +97,9 @@ import { Reading } from './measures';
<tr>
<th scope="row">
{{ row.label }}
@if (row.hint) {
<span class="hint">{{ row.hint }}</span>
}
@if (row.none) {
<span class="none">{{ row.none }}</span>
} @else {
@@ -77,7 +121,7 @@ import { Reading } from './measures';
></span>
}
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m"></span>
<span class="mark" [style.left.%]="m" [style.background]="t.markColor"></span>
}
</span>
}
@@ -89,6 +133,9 @@ import { Reading } from './measures';
}
</tbody>
</table>
@if (t.note) {
<p class="state">{{ t.note }}</p>
}
@if (t.legend; as legend) {
<p class="legend">
@for (l of legend; track l.label) {
@@ -157,6 +204,103 @@ import { Reading } from './measures';
white-space: normal;
width: 60%;
}
.axis {
column-gap: 8px;
display: grid;
font-size: 12px;
grid-template-columns: var(--name-width) 1fr var(--value-width);
margin: 12px 0 2px;
}
.ticks {
height: 1.2em;
position: relative;
}
.ticks span {
white-space: nowrap;
position: absolute;
transform: translateX(-50%);
}
.ticks span:first-child {
transform: none;
}
.ticks span:last-child {
transform: translateX(-100%);
}
.group {
margin: 6px 0 14px;
}
.group h4 {
font-size: 0.95rem;
margin: 0 0 4px;
}
.group .n,
.group .hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
font-size: 0.8em;
font-weight: 400;
margin-left: 8px;
}
.row {
align-items: center;
column-gap: 8px;
display: grid;
font-size: 0.9rem;
grid-template-columns: var(--name-width) 1fr var(--value-width);
min-height: 22px;
}
.row .track {
background:
linear-gradient(to right, #d8dde1 1px, transparent 1px) 25% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 50% 0 / 1px 100% no-repeat,
linear-gradient(to right, #d8dde1 1px, transparent 1px) 75% 0 / 1px 100% no-repeat,
rgba(0, 0, 0, 0.06);
display: block;
height: 10px;
}
.row .fill {
display: block;
height: 100%;
}
.row .value {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
:host {
--name-width: 8.5rem;
--value-width: 8.5rem;
}
@media (max-width: 600px) {
:host {
--name-width: 0px;
--value-width: 0px;
}
.axis {
grid-template-columns: 1fr;
}
.axis > span:not(.ticks) {
display: none;
}
.row {
grid-template-areas: 'name value' 'track track';
grid-template-columns: 1fr auto;
padding-bottom: 4px;
}
.row .name {
grid-area: name;
}
.row .value {
grid-area: value;
}
.row .track {
grid-area: track;
}
}
.hint {
color: var(--mat-sys-on-surface-variant, #5f6368);
display: block;
font-size: 0.8em;
}
.track {
background: rgba(0, 0, 0, 0.06);
display: block;
@@ -207,6 +351,8 @@ export class Readings {
readonly hideTitle = input(false);
readonly camaStyle = input(false);
readonly modes = input.required<Mode[]>();
/** The label of the mode a section's selector chose, for the cards that follow it. */
readonly view = input<string>();
readonly loading = input(false);
/** A measure's reading in the applied period, and the figure of a mode that has one. */
readonly read = input.required<(measure: string) => Reading | undefined>();
@@ -214,9 +360,21 @@ export class Readings {
protected readonly chosen = signal('');
protected readonly mode = computed(
() => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0],
() => this.modes().find((m) => m.label === (this.view() || this.chosen())) ?? this.modes()[0],
);
protected readonly groups = computed(() => grouped(this.mode(), this.read()));
protected readonly table = computed(() => bars(this.mode(), this.read()));
/** The bars of a scenarios figure need more room than a donut. */
protected readonly height = computed(() => {
const m = this.mode();
if (m.kind !== 'figure' || m.figure !== 'scenarios') return 300;
const groups = (this.figure()?.data[0] as { y?: unknown[] } | undefined)?.y?.length ?? 3;
return Math.max(360, 190 + 44 * groups); // a slim bar per group, and room for legend and axis
});
/** What the card says about the categories it does not draw. */
protected readonly hidden = computed(() => hiddenNote(this.mode(), this.read()));
/** Patients in the period but no classification published: say it, do not draw nothing. */
protected readonly missing = computed(() => unavailable(this.mode(), this.read()));
protected readonly figure = computed(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
);
+35 -3
View File
@@ -31,6 +31,7 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
[headline]="headlineOf(s)"
[note]="s.note ?? ''"
[modes]="s.modes"
[view]="view()"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
@@ -71,9 +72,25 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
} @else {
<h2>{{ s.title }}</h2>
@if (s.kind === 'columns') {
@if (s.views) {
<mat-button-toggle-group
class="views"
[attr.aria-label]="s.viewsLabel ?? s.title"
[value]="picked() || s.views[0]"
(change)="picked.set($event.value)"
>
@for (v of s.views; track v) {
<mat-button-toggle [value]="v">{{ v }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
<div class="columns">
@for (inner of s.sections; track $index) {
<app-section [section]="inner" [of]="of()" />
<app-section
[section]="inner"
[of]="of()"
[view]="inner.follows ? picked() || s.views?.[0] : undefined"
/>
}
</div>
} @else {
@@ -101,6 +118,10 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
margin-top: 24px;
min-width: 0;
}
.views {
flex-wrap: wrap;
margin: 4px 0 8px;
}
.title {
font-size: 18px;
font-weight: 500;
@@ -122,6 +143,10 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
export class ReadingsSection {
readonly section = input.required<Shown>();
readonly of = input.required<Source>();
/** The mode a card of a `columns` section takes from the section's selector (its label). */
readonly view = input<string>();
/** The view a columns section's selector has chosen. */
protected readonly picked = signal('');
protected readonly chosen = signal('');
protected hasCamaHeading(s: ReadingsCard): boolean {
@@ -142,8 +167,15 @@ export class ReadingsSection {
const r = this.of().reading(mode.measure);
const measure = this.of().measure(mode.measure);
if (!measure || !r?.populations['initial-population']) return undefined;
if (mode.figure === 'donut') return donut(measure, r);
if (mode.figure === 'donut') return donut(measure, r, 'category', mode.colors);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(r, { groups: [], categories }, 'follow_up_status', name);
return scenarioBars(
r,
{ groups: [], categories },
mode.stratum ?? 'follow_up_status',
name,
mode.order,
{ fill: mode.complete, ofAll: mode.ofAll },
);
});
}
+130
View File
@@ -0,0 +1,130 @@
import { HttpErrorResponse } from '@angular/common/http';
import type { Parameters } from 'fhir/r4';
import { eligibilityFailure, eligibilityView } from './eligibility';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
const candidate = (
scenario: string,
date: string,
eligible: boolean,
criteria: string[] = [],
sample?: string,
display?: string,
) =>
part('candidate', {
part: [
part('scenario', { valueCoding: { system: SCENARIOS, code: scenario, display } }),
part('index-date', { valueDate: date }),
...(sample ? [part('index-sample-id', { valueString: sample })] : []),
part('eligible', { valueBoolean: eligible }),
...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERIA, code: c } })),
],
});
const answer = (status: string, ...candidates: object[]): Parameters =>
({
resourceType: 'Parameters',
parameter: [
part('status', { valueCode: status }),
part('patient', { valueReference: { reference: 'Patient/p' } }),
part('cutoff', { valueDate: '2026-12-02' }),
...candidates,
],
}) as Parameters;
// Each test fails if the section merged visits, dropped a reason or read silence as eligibility.
describe('the eligibility answer as the section shows it', () => {
it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate(
'post_colposcopy',
'2020-08-10',
false,
['cancer_history', 'outcome_by_index', 'prior_treatment'],
'2020-08-10',
),
candidate('surveillance', '2024-01-05', true, [], 'a'),
candidate('surveillance', '2025-03-01', false, ['no_index_result'], 'b'),
candidate('post_colposcopy', '2022-02-02', true, [], '2022-02-02'),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.cutoff).toBe('2026-12-02');
expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([
['post_colposcopy', 'Postcolposcopia', 2],
['surveillance', 'Vigilancia', 2],
]);
const post = view.groups[0].visits; // newest visit first
expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([
['2022-02-02', true, []],
['2020-08-10', false, ['cancer_history', 'outcome_by_index', 'prior_treatment']],
]);
expect(post[1].reasons[0].text).toBe('Antecedente de cáncer cervicouterino');
expect(view.groups[1].visits.map((v) => v.sampleId)).toEqual(['b', 'a']);
});
it('the backend decides: a visit it calls eligible is eligible, one with reasons is not derived', () => {
const view = eligibilityView(answer('evaluated', candidate('survival', '2025-01-01', true)));
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups[0].visits[0]).toMatchObject({
eligible: true,
reasons: [],
sampleId: undefined,
});
});
it('without candidates it says so, which is not eligibility', () => {
expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' });
});
it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => {
for (const bad of [
null,
undefined,
{} as any,
{ resourceType: 'Bundle' } as any,
answer('evaluated'),
answer('other', candidate('survival', '2025-01-01', true)),
answer('evaluated', part('candidate', { part: [] })),
])
expect(eligibilityView(bad)).toEqual({ kind: 'unavailable' });
});
it('unknown codes show the display the API gave, else the code, and keep the code', () => {
const view = eligibilityView(
answer(
'evaluated',
candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'),
candidate('other_scenario', '2025-01-02', false, ['another_rule']),
),
);
if (view.kind !== 'evaluated') throw new Error(view.kind);
expect(view.groups.map((g) => [g.code, g.text])).toEqual([
['new_scenario', 'Escenario nuevo'],
['other_scenario', 'other_scenario'],
]);
expect(view.groups[1].visits[0].reasons).toEqual([
{ code: 'another_rule', text: 'another_rule' },
]);
});
});
describe('what a failed call is', () => {
const failure = (status: number, error: unknown = null) =>
eligibilityFailure(new HttpErrorResponse({ status, error }));
it('a 409 asks for the gold update and keeps the backend diagnostics', () => {
expect(
failure(409, {
resourceType: 'OperationOutcome',
issue: [{ code: 'conflict', diagnostics: 'rebuild gold.cacu_eligibility' }],
}),
).toEqual({ kind: 'gold', text: 'rebuild gold.cacu_eligibility' });
expect(failure(409)).toEqual({ kind: 'gold', text: undefined });
});
it('404 and 422 are "unavailable"; any other status or no connection is a communication error', () => {
expect(failure(404)).toEqual({ kind: 'unavailable' });
expect(failure(422)).toEqual({ kind: 'unavailable' });
expect(failure(500)).toEqual({ kind: 'error' });
expect(failure(0)).toEqual({ kind: 'error' });
expect(eligibilityFailure(new Error('boom'))).toEqual({ kind: 'error' });
});
});
+252
View File
@@ -0,0 +1,252 @@
import { HttpErrorResponse } from '@angular/common/http';
import { Component, input } from '@angular/core';
import type { Parameters, ParametersParameter } from 'fhir/r4';
/** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */
export const SCENARIO_TEXT: Record<string, string> = {
surveillance: 'Vigilancia',
pre_colposcopy: 'Precolposcopia',
post_colposcopy: 'Postcolposcopia',
post_colposcopy_second_visit: 'Segunda visita postcolposcopia',
post_treatment: 'Postratamiento',
survival: 'Supervivencia',
};
/** The exclusion criteria the backend publishes, as the screens say them. */
export const CRITERION_TEXT: Record<string, string> = {
hysterectomy: 'Histerectomía previa al índice',
under_18: 'Edad menor de 18 años al índice',
prior_outcome: 'Resultado CIN2+ previo al índice',
no_index_result: 'Sin resultado de citología o VPH en la visita índice',
unreported_biopsy: 'Biopsia solicitada sin resultado',
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
cancer_history: 'Antecedente de cáncer cervicouterino',
prior_treatment: 'Tratamiento previo a la visita índice',
no_referral: 'Sin resultado que sustente la referencia a colposcopia',
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
no_birth_date: 'Fecha de nacimiento desconocida',
died_by_index: 'Defunción en o antes de la visita índice',
};
export interface Reason {
/** the API's code, untouched */
code: string;
text: string;
}
export interface Visit {
indexDate: string;
/** the sample the visit is evaluated at, when the backend names one */
sampleId?: string;
/** the backend's decision; it is never derived from the reasons */
eligible: boolean;
reasons: Reason[];
}
export interface ScenarioGroup {
code: string;
text: string;
visits: Visit[];
}
/** What the section can be in; none of them says "eligible" unless the backend did. */
export type EligibilityState =
| { kind: 'loading' }
| { kind: 'error' }
| { kind: 'unavailable' }
| { kind: 'gold'; text?: string }
| { kind: 'none'; cutoff?: string }
| { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] };
type Part = ParametersParameter;
const value = (p?: Part): unknown =>
p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueBoolean ?? undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const coding = (p?: Part) => p?.valueCoding;
/** The answer of `$eligibility`, grouped by scenario and keeping the visits apart: each visit has
* its own decision and its own reasons. A code the screens do not know shows the display the API
* gave, else the code itself. An answer that is not what the contract says is "unavailable". */
export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
const top = answer?.parameter;
if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' };
const status = value(named(top, 'status')[0]);
const cutoff = value(named(top, 'cutoff')[0]) as string | undefined;
const candidates = named(top, 'candidate');
if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff };
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
const groups = new Map<string, ScenarioGroup>();
for (const c of candidates) {
const scenario = coding(named(c.part, 'scenario')[0]);
const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined;
const eligible = value(named(c.part, 'eligible')[0]);
if (!scenario?.code || !indexDate || typeof eligible !== 'boolean')
return { kind: 'unavailable' };
const group = groups.get(scenario.code) ?? {
code: scenario.code,
text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code,
visits: [],
};
groups.set(scenario.code, group);
group.visits.push({
indexDate,
sampleId: value(named(c.part, 'index-sample-id')[0]) as string | undefined,
eligible,
reasons: named(c.part, 'criterion').flatMap((r) => {
const k = coding(r);
return k?.code
? [{ code: k.code, text: CRITERION_TEXT[k.code] ?? k.display ?? k.code }]
: [];
}),
});
}
for (const g of groups.values()) g.visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate));
return { kind: 'evaluated', cutoff, groups: [...groups.values()] };
}
/** What the answer's failure says: the gold must be updated (409), the patient has no such
* operation (404, 422), or the call itself failed (anything else, including no connection). */
export function eligibilityFailure(error: unknown): EligibilityState {
if (error instanceof HttpErrorResponse) {
if (error.status === 409) {
const issue = (error.error as { issue?: { diagnostics?: string }[] } | null)?.issue?.[0];
return { kind: 'gold', text: issue?.diagnostics };
}
if (error.status === 404 || error.status === 422) return { kind: 'unavailable' };
}
return { kind: 'error' };
}
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
/** "Elegibilidad por escenario clínico": the decisions the backend publishes for each indexed visit,
* one scenario at a time. It shows them; it decides nothing. */
@Component({
selector: 'app-eligibility',
template: `
@let s = state();
@switch (s.kind) {
@case ('loading') {
<p class="state" role="status" data-state="loading">Consultando la elegibilidad…</p>
}
@case ('error') {
<p class="state" role="alert" data-state="error">
No se pudo consultar la elegibilidad. Intente de nuevo más tarde.
</p>
}
@case ('unavailable') {
<p class="state" role="status" data-state="unavailable">
Información de elegibilidad no disponible para esta paciente.
</p>
}
@case ('gold') {
<p class="state" role="status" data-state="gold">
La elegibilidad requiere actualizar la capa gold del servidor; todavía no está disponible.
</p>
@if (s.text) {
<p class="muted detail">{{ s.text }}</p>
}
}
@case ('none') {
<p class="state" role="status" data-state="none">
Sin candidatos: la paciente no tiene visitas indexadas en estos escenarios
@if (s.cutoff) {
a la fecha de corte {{ s.cutoff }}
}
. Esto no significa que sea elegible.
</p>
}
@case ('evaluated') {
@for (g of s.groups; track g.code) {
<details class="scenario" [attr.data-scenario]="g.code" [open]="g.visits.length <= 2">
<summary>
<strong>{{ g.text }}</strong>
<span class="muted">
· {{ plural(g.visits.length, 'visita', 'visitas') }} ·
{{ plural(count(g, true), 'elegible', 'elegibles') }},
{{ plural(count(g, false), 'no elegible', 'no elegibles') }}
</span>
</summary>
<ul class="visits">
@for (v of g.visits; track $index) {
<li class="visit" [attr.data-eligible]="v.eligible">
<p class="head">
<span class="badge" [class.ok]="v.eligible">{{
v.eligible ? 'Elegible' : 'No elegible'
}}</span>
Fecha índice {{ v.indexDate }}
<span class="muted"
>· {{ v.sampleId ? 'Muestra ' + v.sampleId : 'Sin muestra asociada' }}</span
>
</p>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivos de exclusión">
@for (r of v.reasons; track r.code) {
<li [attr.data-code]="r.code">{{ r.text }}</li>
}
</ul>
}
</li>
}
</ul>
</details>
}
@if (s.cutoff) {
<p class="muted note">Visitas hasta la fecha de corte {{ s.cutoff }}.</p>
}
}
}
`,
styles: `
.note,
.detail {
font-size: 12px;
}
.state {
margin: 8px 0;
}
.scenario {
border-top: 1px solid #dce3e7;
padding: 6px 0;
}
.scenario summary {
cursor: pointer;
}
.visits {
list-style: none;
margin: 6px 0 0;
padding: 0;
}
.visit {
padding: 4px 0 4px 12px;
}
.head {
margin: 0;
}
.badge {
background: #f3d6dc;
border-radius: 10px;
color: #7a1f36;
font-size: 12px;
font-weight: 500;
margin-right: 6px;
padding: 1px 8px;
}
.badge.ok {
background: #dcefe4;
color: #1d5a3b;
}
.why {
margin: 2px 0 0;
padding-left: 22px;
}
`,
})
export class Eligibility {
readonly state = input.required<EligibilityState>();
protected plural = plural;
protected count(g: ScenarioGroup, eligible: boolean) {
return g.visits.filter((v) => v.eligible === eligible).length;
}
}
+31
View File
@@ -0,0 +1,31 @@
import type { EligibilityState, Visit } from './eligibility';
import { ineligibility } from './ineligibility';
const visit = (indexDate: string, ...reasons: string[]): Visit => ({
indexDate,
eligible: !reasons.length,
reasons: reasons.map((text) => ({ code: text, text })),
});
const state: EligibilityState = {
kind: 'evaluated',
groups: [
{
code: 'pre_colposcopy',
text: 'Precolposcopia',
visits: [visit('2025-01-01', 'Histerectomía previa al índice'), visit('2024-01-01')],
},
{ code: 'post_treatment', text: 'Postratamiento', visits: [visit('2025-01-01', 'Otro')] },
],
};
describe('ineligibility', () => {
it('speaks only when she is not eligible in her own scenario', () => {
expect(ineligibility(state, 'pre_colposcopy', '2025-06-01')).toBe(
'No disponible por: Histerectomía previa al índice.',
);
expect(ineligibility(state, 'pre_colposcopy', '2024-06-01')).toBeUndefined();
expect(ineligibility(state, 'post_colposcopy', '2025-06-01')).toBeUndefined();
expect(ineligibility(state, 'case', '2025-06-01')).toBeUndefined();
expect(ineligibility({ kind: 'error' }, 'pre_colposcopy', '2025-06-01')).toBeUndefined();
});
});
+31
View File
@@ -0,0 +1,31 @@
import type { EligibilityState } from './eligibility';
/** The `$eligibility` scenarios that stand for each follow-up status, the first that has a
* visit speaking for her. A case has no disease-risk estimate to be eligible for. */
const SCENARIOS: Record<string, string[]> = {
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
post_colposcopy: ['post_colposcopy'],
post_treatment: ['post_treatment'],
};
/** What the risk section says when she is not eligible in her clinical scenario, from its latest
* visit indexed by `day`; nothing when she is eligible or the backend has no visit of it. */
export function ineligibility(
state: EligibilityState,
status: string,
day: string,
): string | undefined {
if (state.kind !== 'evaluated') return undefined;
for (const scenario of SCENARIOS[status] ?? []) {
// visits come latest first
const latest = state.groups
.find((g) => g.code === scenario)
?.visits.find((v) => v.indexDate <= day);
if (latest) {
return latest.eligible
? undefined
: `No disponible por: ${latest.reasons.map((r) => r.text).join('; ')}.`;
}
}
return undefined;
}
+173 -58
View File
@@ -107,23 +107,22 @@
</mat-card-content>
</mat-card>
}
@if (stages(); as s) {
<mat-card appearance="outlined" class="wide" data-section="etapas">
<mat-card-header><mat-card-title>Etapas del tamizaje</mat-card-title></mat-card-header>
<mat-card-content>
<app-stages [stages]="s" [detail]="true" />
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
</mat-card-content>
</mat-card>
}
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content>
@if (stages(); as s) {
<div class="export-actions">
<button mat-stroked-button type="button" [disabled]="saving()" (click)="save()">
Exportar PDF
</button>
</div>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
<div data-section="etapas">
<app-stages [stages]="s" [detail]="true" />
</div>
}
<table class="plain">
<thead>
<tr>
@@ -172,7 +171,19 @@
<td class="nowrap">{{ t.date }}</td>
<td>{{ t.kind }}</td>
<td class="nowrap">{{ t.reported ?? 'Pendiente' }}</td>
<td>{{ t.results.join(' · ') || '—' }}</td>
<td>
{{ t.results.join(' · ') || '—' }}
@if (t.findings.length) {
<details class="findings">
<summary>Hallazgos ({{ t.findings.length }})</summary>
<ul>
@for (f of t.findings; track $index) {
<li>{{ f }}</li>
}
</ul>
</details>
}
</td>
</tr>
} @empty {
<tr>
@@ -184,51 +195,117 @@
</mat-card-content>
</mat-card>
<mat-card appearance="outlined" class="wide">
<mat-card-header
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
<app-risk-scales [scales]="scales()" />
@if (models().length) {
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Probabilidad</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (m of models(); track m.model) {
@for (p of m.predictions; track p.years) {
@if (forms().length) {
<mat-card appearance="outlined" class="wide" data-section="antecedentes">
<mat-card-header
><mat-card-title
>Antecedentes y evaluación ginecológica</mat-card-title
></mat-card-header
>
<mat-card-content>
<p class="muted route-note">
Datos declarados en el formulario de la citología: no son diagnósticos confirmados.
Cada dato pertenece al formulario de la toma que se indica.
</p>
@let f = forms()[0];
<h3>Citología cervical · toma {{ f.date }}</h3>
<dl class="facts">
@for (a of antecedents; track a.field) {
<div>
<dt>{{ a.title }}</dt>
<dd>{{ f.values[a.field] ?? 'No documentado' }}</dd>
</div>
}
</dl>
@if (forms().length > 1) {
<details class="findings">
<summary>Formularios anteriores ({{ forms().length - 1 }})</summary>
<table class="plain">
<thead>
<tr>
<td>{{ $first ? m.text : '' }}</td>
<td>{{ $first ? m.index : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }}
%
} @else {
—
}
</td>
<th>Toma</th>
@for (a of antecedents; track a.field) {
<th>{{ a.title }}</th>
}
</tr>
}
}
</tbody>
</table>
<app-plot [figure]="curve()" [height]="300" />
</thead>
<tbody>
@for (o of forms().slice(1); track o.date) {
<tr>
<td class="nowrap">{{ o.date }}</td>
@for (a of antecedents; track a.field) {
<td>{{ o.values[a.field] ?? 'No documentado' }}</td>
}
</tr>
}
</tbody>
</table>
</details>
}
</mat-card-content>
</mat-card>
}
<mat-card appearance="outlined" class="wide" data-section="riesgos">
<mat-card-content>
@if (riskExclusion(); as reason) {
<p role="status">{{ reason }}</p>
} @else {
<app-risk-scales [groups]="groups()" />
}
@if (riskModels().length) {
<details data-section="modelos">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Probabilidad</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (m of riskModels(); track m.model) {
@for (p of m.predictions; track p.years) {
<tr>
<td>{{ $first ? m.text : '' }}</td>
<td>{{ $first ? m.index : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{
p.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
}
</tbody>
</table>
</details>
}
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
<details class="curves" open data-section="curvas">
<summary>Curvas de probabilidad con su intervalo</summary>
@if (riskSeries.value()?.length) {
<app-risk-series [series]="riskSeries.value()!" />
} @else {
<app-plot [figure]="curve()" [height]="300" />
}
</details>
}
@if (!riskModels().length && !riskExclusion()) {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
</mat-card-content>
</mat-card>
@if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -476,11 +553,22 @@
</mat-card-content>
</mat-card>
}
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) {
@if (models().some((m) => m.model.endsWith('.survival'))) {
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header><mat-card-title>Riesgo de muerte</mat-card-title></mat-card-header>
<mat-card-header>
<mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia por escenario clínico' : 'Riesgo de muerte'
}}</mat-card-title>
</mat-card-header>
<mat-card-content>
<h3>Análisis de supervivencia</h3>
@if (domain() === 'cacu') {
<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()) {
<app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (survival.value(); as s) {
@@ -490,17 +578,44 @@
<li>{{ name }}</li>
}
</ul>
@if (s.methods.length) {
<h3>Métodos</h3>
<ul class="scenarios methods">
@for (name of s.methods; track name) {
<li>{{ name }}</li>
}
</ul>
}
@for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="340" />
} @empty {
<p class="muted">
Sus escenarios no tienen fallecimientos suficientes para trazar curvas.
}
@for (name of s.unavailable; track name) {
<h4>{{ name }}</h4>
<p class="muted">No disponible: datos insuficientes.</p>
}
@for (u of s.insufficient; track u.name) {
<h4>{{ u.name }}</h4>
<p class="muted" data-state="insuficiente">{{ insufficientText(u) }}</p>
}
@for (name of s.missing; track name) {
<h4>{{ name }}</h4>
<p class="muted" data-state="sin-informacion">
Sin información de este escenario en el informe del modelo.
</p>
}
<app-factores [rows]="s.factors" />
} @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else {
<p class="muted" data-state="sin-informe">
@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>
+40
View File
@@ -98,3 +98,43 @@ h1 .id {
margin-left: var(--space-2);
vertical-align: middle;
}
.export-actions {
display: flex;
justify-content: flex-end;
margin-bottom: var(--space-3);
}
.route-note {
font-size: 12px;
margin: var(--space-2) 0 var(--space-3);
}
.findings {
margin-top: 4px;
summary {
color: var(--color-text-secondary);
cursor: pointer;
font-size: 13px;
}
ul {
margin: 4px 0 0;
padding-left: 18px;
}
}
.curves {
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 12px;
padding: 8px 12px;
summary {
cursor: pointer;
font-weight: 500;
}
}
.curve-text {
margin: 8px 0;
padding-left: 18px;
}
+176 -64
View File
@@ -13,6 +13,8 @@ import type {
RiskAssessment,
} from 'fhir/r4';
import { Api } from '../api/api';
import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study';
import { readReport$Json } from '../api/fn/models/read-report-json';
@@ -21,7 +23,16 @@ import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { savePdf } from '../export';
import { recordSheets } from './record-sheets';
import { riskScales, RiskScales } from './risk-scales';
import { HttpClient } from '@angular/common/http';
import type { Parameters as FhirParameters } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve';
import { isRiskModel, riskGroups, riskScales, RiskScales } from './risk-scales';
import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -51,8 +62,23 @@ function shown(o: Observation): string {
return o.valueString ?? o.valueDateTime ?? '';
}
/** A report's Observations as facts of its study's form (record-groups). */
function facts(observations: Observation[]): Fact[] {
return observations.map((o) => ({
...split(code(o.code) ?? ''),
title: label(o.code),
value: shown(o),
}));
}
/** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */
/** The names of the methods the figures draw, each once. */
function methods(figures: { figure: { data: unknown[] } }[]): string[] {
const names = figures.flatMap((f) => f.figure.data.map((t) => (t as { name?: string }).name));
return [...new Set(names.filter((n): n is string => !!n))];
}
@Component({
selector: 'app-paciente',
imports: [
@@ -65,6 +91,7 @@ function shown(o: Observation): string {
RouterLink,
Plot,
RiskScales,
RiskSeries,
Stages,
],
templateUrl: './paciente.html',
@@ -73,6 +100,8 @@ function shown(o: Observation): string {
export class Paciente {
private readonly fhir = inject(Fhir);
private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
readonly domain = input.required<string>();
readonly id = input.required<string>();
/** The follow-up list she was opened from: its window (months) and cut-off. */
@@ -127,8 +156,25 @@ export class Paciente {
})),
].sort((a, b) => b.date.localeCompare(a.date));
});
private 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()));
/** Why she has no risk estimate; nothing when she is eligible. Only while the backend gives
* no decision (failure, gold not updated) is the hysterectomy of her record held against it. */
protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined;
const patient = this.patient();
const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const state = this.eligibility();
if (state.kind === 'evaluated' || state.kind === 'none') {
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
return ineligibility(state, status, index);
}
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index
? `No disponible por: histerectomía registrada el ${recorded}.`
: 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(
@@ -137,8 +183,63 @@ export class Paciente {
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
});
/** 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 scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.models()) : [],
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
);
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */
protected readonly groups = computed(() =>
this.domain() === 'cacu' ? riskGroups(this.riskModels()) : [],
);
/** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({
params: () =>
this.domain() === 'cacu'
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
: undefined,
loader: async ({ params }): Promise<Series[] | undefined> => {
try {
const answer = await firstValueFrom(
this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
{
params: Object.fromEntries(
Object.entries({
cutoff: params.cutoff,
sample: params.sample?.slice(0, 10),
}).filter((e): e is [string, string] => !!e[1]),
),
},
),
);
return parseSeries(answer);
} catch {
return undefined;
}
},
});
/** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a
* state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */
private readonly eligibilityData = resource({
params: () => (this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined),
loader: async ({ params }): Promise<EligibilityState> => {
try {
const answer = await this.api.invoke(cacuEligibility, {
domain: 'cacu' as Domain,
id: params.id,
cutoff: params.cutoff,
});
return eligibilityView(answer as FhirParameters);
} catch (error) {
return eligibilityFailure(error);
}
},
});
protected readonly eligibility = computed<EligibilityState>(() =>
this.eligibilityData.isLoading()
? { kind: 'loading' }
: (this.eligibilityData.value() ?? { kind: 'loading' }),
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
@@ -157,11 +258,13 @@ export class Paciente {
['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()],
];
if (this.riskExclusion()) facts.push(['Evaluación de riesgo', this.riskExclusion()]);
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.forms(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
@@ -174,25 +277,57 @@ export class Paciente {
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
return d.reports.map((r) => {
return d.reports.flatMap((r) => {
const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[];
return {
// the study's own results; the form's antecedents are in their own section and the extra
// findings are collapsed (record-groups)
const { hpv, rest } = hpvApart(facts(results));
const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
status: r.status,
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
results: results.map((o) => {
const [name, value] = [label(o.code), shown(o)];
return value.startsWith(name) ? value : `${name}: ${value}`;
}),
results: found.results,
findings: found.findings,
};
// an HPV result is a study of its own: its own row, only when there is one
return hpv.length
? [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]
: [row];
});
});
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
* opened at first, each with its day. They are statements of the form, not confirmed diagnoses. */
protected readonly forms = computed(() => {
const d = this.data.value();
if (!d || this.domain() !== 'cacu') return [];
const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology');
const first = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return [first, ...cytologies.filter((r) => r !== first)]
.filter((r) => !!r)
.map((r) => {
const found = group(
facts(
(r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[],
),
).antecedents;
return {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
values: found,
};
})
.filter((f) => ANTECEDENTS.some((a) => f.values[a.field]));
});
protected readonly antecedents = ANTECEDENTS;
/** One model's latest risk assessment per model. */
protected readonly models = computed(() => {
if (this.riskExclusion()) return [];
const latest = new Map<string, RiskAssessment>();
for (const r of this.data.value()?.risks ?? []) {
const key = code(r.method) ?? '';
@@ -256,6 +391,10 @@ export class Paciente {
return {
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
scenarios: m.scenarios,
unavailable: [] as string[],
insufficient: [] as Insufficient[],
missing: [] as string[],
methods: [] as string[],
figures: mine(r['escenarios'] ?? []).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
@@ -266,17 +405,29 @@ export class Paciente {
),
};
}
const drawn = mine((report?.['escenarios'] ?? []) as any[]);
const figures = drawn.map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
);
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
// CaCu: the report says which scenarios lack deaths (`escenarios_sin_curvas`); one it does not
// mention is not "insufficient", it is absent from the report. Other domains keep one list.
const { insufficient, missing } =
domain === 'cacu' ? sortUndrawn(report, undrawn) : { insufficient: [], missing: [] };
return {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
scenarios: m.scenarios,
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
),
figures,
// her scenarios the report draws no curve for
unavailable: domain === 'cacu' ? [] : undrawn,
insufficient,
missing,
methods: methods(figures),
};
},
});
@@ -389,54 +540,15 @@ export class Paciente {
}
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
protected readonly curve = computed<Figure>(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
return {
data: models.flatMap((m, i) => {
const x = m.predictions.map((p) => p.years);
const color = PALETTE[i % PALETTE.length];
return [
{
x,
y: m.predictions.map((p) => (p.high ?? p.p) * 100),
mode: 'lines',
line: { width: 0 },
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: m.predictions.map((p) => (p.low ?? p.p) * 100),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
fillcolor: color + '33',
showlegend: false,
hoverinfo: 'skip',
},
{
x,
y: m.predictions.map((p) => p.p * 100),
mode: 'lines+markers',
name: m.text.replace(/ v\d+$/, ''),
line: { color },
},
];
}),
layout: {
xaxis: { title: { text: 'Años desde la fecha índice' }, dtick: 1 },
// At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: {
title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, this.top() * 110)],
tickformat: '.1f',
},
},
};
});
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
private top(): number {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
return Math.max(
0,
...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)),
);
}
protected readonly insufficientText = insufficientText;
protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES;
protected readonly identity = computed(() => {
+77
View File
@@ -0,0 +1,77 @@
import { ANTECEDENTS, group, split } from './record-groups';
const fact = (study: string, field: string, title: string, value: string) => ({
study,
field,
title,
value,
});
describe('the record of a cytology by what its facts are', () => {
it('splits a catalog code into its study and its field', () => {
expect(split('cervical_cytology.hpv_16')).toEqual({
study: 'cervical_cytology',
field: 'hpv_16',
});
expect(split('plain')).toEqual({ study: '', field: 'plain' });
});
it('keeps the form antecedents apart from the results and the findings', () => {
const found = group([
fact(
'cervical_cytology',
'screening_history',
'Detección de cáncer de cérvix',
'Primera vez en la vida',
),
fact(
'cervical_cytology',
'gynecologic_condition',
'Condición ginecoobstétrica a la detección',
'DIU in situ',
),
fact('cervical_cytology', 'presenting_symptom', 'Actualmente presenta', 'Flujo'),
fact('cervical_cytology', 'cervix_appearance', 'A la exploración se observa', 'Cuello sano'),
fact('cervical_cytology', 'adequacy', 'Calidad de la muestra', 'Satisfactoria'),
fact(
'cervical_cytology',
'result',
'Resultado (Bethesda)',
'Negativo para lesión intraepitelial o malignidad',
),
fact('cervical_cytology', 'hpv', 'VPH de alto riesgo', 'negativo'),
fact('cervical_cytology', 'findings', 'Hallazgos adicionales', 'Inflamación.'),
fact('cervical_cytology', 'finding_inflammation', 'Hallazgo: inflamación', 'positivo'),
]);
expect(Object.keys(found.antecedents)).toEqual(ANTECEDENTS.map((a) => a.field));
expect(found.antecedents['gynecologic_condition']).toBe('DIU in situ');
expect(found.results).toEqual([
'Calidad de la muestra: Satisfactoria',
'Resultado (Bethesda): Negativo para lesión intraepitelial o malignidad',
'VPH de alto riesgo: negativo',
]);
expect(found.findings).toEqual(['Texto del informe: Inflamación.', 'Inflamación']);
});
it('nothing is lost: every fact lands in exactly one place', () => {
const facts = [
fact('cervical_cytology', 'screening_history', 'a', '1'),
fact('cervical_cytology', 'result', 'b', '2'),
fact('cervical_cytology', 'finding_atrophy', 'Hallazgo: atrofia', 'positivo'),
fact('cervical_biopsy', 'histology', 'Histología', 'LIEAG'),
];
const found = group(facts);
expect(
Object.keys(found.antecedents).length + found.results.length + found.findings.length,
).toBe(facts.length);
});
it('a study that is not the cytology has no antecedents and no collapsed findings', () => {
const found = group([fact('cervical_biopsy', 'histology', 'Histología', 'LIEAG (CIN 2 y 3)')]);
expect(found.antecedents).toEqual({});
expect(found.findings).toEqual([]);
expect(found.results).toEqual(['Histología: LIEAG (CIN 2 y 3)']);
});
it('a stated finding keeps a value that is not simply "positivo"', () => {
expect(
group([fact('cervical_cytology', 'finding_none', 'Hallazgo: ninguno', 'negativo')]).findings,
).toEqual(['Ninguno: negativo']);
});
});
+56
View File
@@ -0,0 +1,56 @@
/** One field of a study's form as the report's Observation carries it: the catalog's field
* (`cervical_cytology.screening_history`), its title and its value as the screens say it. */
export interface Fact {
study: string;
field: string;
title: string;
value: string;
}
/** What the cytology's form declares of her before and at the sample: her screening history, the
* gynecologic condition she reports, what she presents and what the exploration observed. These are
* statements of the form (not diagnoses), each with its form and day. */
export const ANTECEDENTS: { field: string; title: string }[] = [
{ field: 'screening_history', title: 'Detección de cáncer de cérvix' },
{ field: 'gynecologic_condition', title: 'Condición ginecoobstétrica a la detección' },
{ field: 'presenting_symptom', title: 'Actualmente presenta' },
{ field: 'cervix_appearance', title: 'A la exploración se observa' },
];
/** `cervical_cytology.hpv` as its study and its field. */
export function split(code: string): { study: string; field: string } {
const at = code.indexOf('.');
return at < 0
? { study: '', field: code }
: { study: code.slice(0, at), field: code.slice(at + 1) };
}
/** A report's facts by what they are: the form's antecedents (by field), the results of the study
* itself, and the extra findings (collapsible): the cytologist's text and each stated finding. */
export function group(facts: Fact[]) {
const antecedents: Record<string, string> = {};
const results: string[] = [];
const findings: string[] = [];
for (const f of facts) {
const cytology = f.study === 'cervical_cytology';
if (cytology && ANTECEDENTS.some((a) => a.field === f.field)) antecedents[f.field] = f.value;
else if (cytology && f.field === 'findings') findings.unshift(`Texto del informe: ${f.value}`);
else if (cytology && f.field.startsWith('finding_')) {
const named = f.title.replace(/^Hallazgo: /, '');
const text = named.charAt(0).toUpperCase() + named.slice(1);
findings.push(f.value === 'positivo' ? text : `${text}: ${f.value}`);
} else {
// "BI-RADS 4C", not "BI-RADS: BI-RADS 4C"
results.push(f.value.startsWith(f.title) ? f.value : `${f.title}: ${f.value}`);
}
}
return { antecedents, results, findings };
}
const HPV_FIELDS = ['hpv', 'hpv_16', 'hpv_18'];
/** The cytology report's HPV results, apart from the cytology's own facts. */
export function hpvApart(facts: Fact[]) {
const isHpv = (f: Fact) => f.study === 'cervical_cytology' && HPV_FIELDS.includes(f.field);
return { hpv: facts.filter(isHpv), rest: facts.filter((f) => !isHpv(f)) };
}
+92
View File
@@ -0,0 +1,92 @@
import { recordSheets } from './record-sheets';
describe('the PDF of a record', () => {
const sheets = recordSheets(
[['Nombre', 'Ana']],
[
{
label: 'Toma de muestra',
day: '2026-01-10',
state: 'recorded',
sources: ['cytology-form'],
},
{
label: 'Colposcopía',
day: '2026-02-01',
state: 'inferred',
sources: ['clinical-note', 'biopsy-order'],
},
{
label: 'Reporte de biopsia',
state: 'pending',
requested: '2026-02-05',
sources: ['date-association'],
},
{ label: 'Diagnóstico', state: 'unknown' },
],
[{ date: '2026-03-01', kind: 'Diagnóstico', text: 'N87.9' }],
[
{
date: '2026-01-10',
kind: 'Citología cervical',
reported: '2026-01-20',
results: ['Resultado (Bethesda): LIEAG'],
findings: ['Texto del informe: Inflamación.', 'Inflamación'],
},
],
[
{
date: '2026-01-10',
values: { screening_history: 'Primera vez en la vida', cervix_appearance: 'Cuello sano' },
},
],
[],
);
const by = (title: string) => sheets.find((s) => s.title.startsWith(title))!;
it('keeps every section, in the page order', () => {
expect(sheets.map((s) => s.title.split(' (')[0])).toEqual([
'Datos de la paciente',
'Etapas del tamizaje',
'Historial médico',
'Antecedentes y evaluación ginecológica',
'Pruebas y resultados',
'Riesgos',
]);
});
it('writes each stage with its state, its day or its request, and where it comes from', () => {
expect(by('Etapas').head).toEqual(['Etapa', 'Estado', 'Fecha', 'Procedencia']);
expect(by('Etapas').rows).toEqual([
['Toma de muestra', 'Registrada', '2026-01-10', 'Formulario de citología'],
['Colposcopía', 'Inferida por fechas', '2026-02-01', 'Nota clínica · Orden de biopsia'],
['Reporte de biopsia', 'Pendiente', 'Solicitada el 2026-02-05', 'Asociación por fechas'],
['Diagnóstico', 'Sin dato', '', ''],
]);
});
it('gives the declared antecedents their own sheet, said as declared, with what is not documented', () => {
const s = by('Antecedentes');
expect(s.title).toContain('no son diagnósticos confirmados');
expect(s.head).toEqual([
'Toma',
'Detección de cáncer de cérvix',
'Condición ginecoobstétrica a la detección',
'Actualmente presenta',
'A la exploración se observa',
]);
expect(s.rows).toEqual([
['2026-01-10', 'Primera vez en la vida', 'No documentado', 'No documentado', 'Cuello sano'],
]);
});
it('keeps the results and the extra findings of each test in their own columns', () => {
expect(by('Pruebas').head).toEqual(['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos']);
expect(by('Pruebas').rows).toEqual([
[
'2026-01-10',
'Citología cervical',
'2026-01-20',
'Resultado (Bethesda): LIEAG',
'Texto del informe: Inflamación. · Inflamación',
],
]);
});
});
+33 -5
View File
@@ -1,6 +1,7 @@
import type { Sheet } from '../export';
import type { RiskScale } from './risk-scales';
import { Stage, STATES } from './stages';
import { ANTECEDENTS } from './record-groups';
import { SOURCES, Stage, STATES } from './stages';
const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
@@ -15,6 +16,12 @@ interface Test {
kind: string;
reported?: string;
results: string[];
/** the extra findings (collapsed on the page) */
findings: string[];
}
interface Form {
date: string;
values: Record<string, string | undefined>;
}
/** A patient's record as the tables of her PDF, in the page's order. */
@@ -23,6 +30,7 @@ export function recordSheets(
stages: Stage[],
history: Event[],
tests: Test[],
forms: Form[],
scales: RiskScale[],
): Sheet[] {
return [
@@ -33,18 +41,38 @@ export function recordSheets(
},
{
title: 'Etapas del tamizaje',
head: ['Etapa', 'Estado', 'Fecha'],
rows: stages.map((s) => [s.label, STATES[s.state], s.day ?? '']),
head: ['Etapa', 'Estado', 'Fecha', 'Procedencia'],
rows: stages.map((s) => [
s.label,
STATES[s.state],
s.day ?? (s.requested ? `Solicitada el ${s.requested}` : ''),
(s.sources ?? []).map((c) => SOURCES[c]).join(' · '),
]),
},
{
title: 'Historial médico',
head: ['Fecha', 'Tipo', 'Detalle'],
rows: history.map((h) => [h.date, h.kind, h.text]),
},
{
title:
'Antecedentes y evaluación ginecológica (declarados en el formulario de la citología; no son diagnósticos confirmados)',
head: ['Toma', ...ANTECEDENTS.map((a) => a.title)],
rows: forms.map((f) => [
f.date,
...ANTECEDENTS.map((a) => f.values[a.field] ?? 'No documentado'),
]),
},
{
title: 'Pruebas y resultados',
head: ['Toma', 'Estudio', 'Reporte', 'Resultados'],
rows: tests.map((t) => [t.date, t.kind, t.reported ?? 'Pendiente', t.results.join(' · ')]),
head: ['Toma', 'Estudio', 'Reporte', 'Resultados', 'Hallazgos'],
rows: tests.map((t) => [
t.date,
t.kind,
t.reported ?? 'Pendiente',
t.results.join(' · '),
t.findings.join(' · '),
]),
},
{
title: 'Riesgos',
+260
View File
@@ -0,0 +1,260 @@
import type { Parameters } from 'fhir/r4';
import { groupReference, horizonLabel, outcomeText, referenceView } from './reference-risk';
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
const answer = (...parameter: object[]): Parameters =>
({ resourceType: 'Parameters', parameter }) as Parameters;
const resolved = (comparison: object[] = []) =>
answer(
part('status', { valueCode: 'resolved' }),
part('cutoff', { valueDate: '2026-11-30' }),
part('scenario', {
part: [
part('table', { valueCode: 'screening' }),
part('label', { valueString: 'Tamizaje' }),
part('key', {
part: [
part('name', { valueCode: 'history' }),
part('value', { valueString: 'Cotest-negative' }),
],
}),
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0 }),
...comparison,
],
}),
part('horizon', {
part: [part('years', { valueInteger: 5 }), part('published', { valueBoolean: false })],
}),
);
describe('the reference answer as the section shows it', () => {
it('names the horizons and never calls a year the immediate risk', () => {
expect(horizonLabel(0)).toBe('Inmediato (al índice)');
expect(horizonLabel(1)).toBe('1 año');
expect(horizonLabel(5)).toBe('5 años');
});
it('keeps a published zero as zero and a blank as absent', () => {
const view = referenceView(resolved());
expect(view.horizons.map((h) => [h.years, h.reference, h.published])).toEqual([
[0, 0, true],
[5, undefined, false],
]);
expect(view.scenario).toEqual({
label: 'Tamizaje',
keys: [{ name: 'Antecedente más reciente', value: 'Cotest-negative' }],
});
});
it('reads a comparison with its model, its figures and its reasons, and a difference only when one is given', () => {
const view = referenceView(
resolved([
part('comparison', {
part: [
part('model', { valueCode: 'cacu.cin2_pim' }),
part('title', { valueString: 'Riesgo LIEAG+' }),
part('institutional', { valueDecimal: 0.05 }),
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'outcome_differs' }),
],
}),
]),
);
const [c] = view.horizons[0].comparisons;
expect(c).toMatchObject({
model: 'cacu.cin2_pim',
institutional: 0.05,
status: 'not_comparable',
reasons: ['outcome_differs'],
});
expect(c.differencePp).toBeUndefined();
});
it('an unresolved answer has its state and reasons and no horizons', () => {
const view = referenceView(
answer(
part('status', { valueCode: 'history_not_demonstrable' }),
part('reason', { valueCode: 'no_earlier_test_registered' }),
),
);
expect(view).toMatchObject({
status: 'history_not_demonstrable',
reasons: ['no_earlier_test_registered'],
horizons: [],
used: [],
});
});
});
const cmp = (
model: string,
outcome: string,
status: string,
reasons: string[],
extra: object[] = [],
) =>
part('comparison', {
part: [
part('model', { valueCode: model }),
part('title', { valueString: model }),
part('outcome', { valueString: outcome }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const two = (a: object[], b: object[]) =>
answer(
part('status', { valueCode: 'resolved' }),
part('horizon', {
part: [
part('years', { valueInteger: 0 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.001 }),
...a,
],
}),
part('horizon', {
part: [
part('years', { valueInteger: 5 }),
part('published', { valueBoolean: true }),
part('reference', { valueDecimal: 0.0027 }),
...b,
],
}),
);
describe('outcome names', () => {
it('translates the known outcomes for display and leaves the API identifier untouched', () => {
expect(outcomeText('cancer')).toBe('Cáncer');
expect(outcomeText('CIN2+ within one year')).toBe('CIN2+ en un año');
expect(outcomeText('CIN3+')).toBe('CIN3 o más grave (CIN3+)');
expect(outcomeText('something new')).toBe('something new');
expect(outcomeText(undefined)).toBe('');
const view = referenceView(
two([cmp('m', 'cancer', 'not_comparable', ['outcome_differs'])], []),
);
expect(view.horizons[0].comparisons[0].outcome).toBe('cancer');
});
});
describe('grouping the comparison', () => {
const reasons = ['outcome_differs', 'population_not_verified'];
it('keeps every model, horizon, value and interval, and says shared reasons once', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN2+',
'not_comparable',
[...reasons, 'index_date_differs'],
[part('institutional', { valueDecimal: 0.05 })],
),
cmp('b', 'cancer', 'not_comparable', reasons),
],
[
cmp('a', 'CIN2+', 'not_comparable', reasons, [
part('institutional', { valueDecimal: 0.07 }),
part('institutional-low', { valueDecimal: 0.05 }),
part('institutional-high', { valueDecimal: 0.09 }),
]),
cmp('b', 'cancer', 'not_comparable', [...reasons, 'horizon_not_published_by_model']),
],
),
),
);
expect(g.reference.map((r) => [r.years, r.reference])).toEqual([
[0, 0.001],
[5, 0.0027],
]);
expect(g.common).toEqual(reasons); // every model gives them
expect(g.models.map((m) => [m.model, m.outcome, m.rows.length])).toEqual([
['a', 'CIN2+', 2],
['b', 'cancer', 2],
]);
expect(g.models[0].reasons).toEqual([]); // nothing else shared by both of a's horizons
expect(g.models[0].rows[0].reasons).toEqual(['index_date_differs']);
expect(g.models[0].rows[1]).toMatchObject({
institutional: 0.07,
low: 0.05,
high: 0.09,
reasons: [],
});
expect(g.models[1].rows[1].reasons).toEqual(['horizon_not_published_by_model']);
});
it('never merges across outcomes: reasons are only shared where every compared row has them', () => {
const g = groupReference(
referenceView(
two(
[
cmp('a', 'CIN2+', 'not_comparable', ['outcome_differs']),
cmp('b', 'cancer', 'not_comparable', ['no_reference']),
],
[],
),
),
);
expect(g.common).toEqual([]);
expect(g.models.flatMap((m) => m.rows.flatMap((r) => r.reasons))).toEqual([
'outcome_differs',
'no_reference',
]);
});
it('a comparable row keeps its difference and a missing interval stays missing', () => {
const g = groupReference(
referenceView(
two(
[
cmp(
'a',
'CIN3+',
'comparable',
[],
[
part('institutional', { valueDecimal: 0.01 }),
part('difference-pp', { valueDecimal: 0.9 }),
],
),
],
[],
),
),
);
expect(g.models[0].rows[0]).toMatchObject({
status: 'comparable',
differencePp: 0.9,
low: undefined,
});
});
it('without a model it says so once, with its reasons', () => {
const g = groupReference(
referenceView(
two(
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
[
part('comparison', {
part: [
part('status', { valueCode: 'not_comparable' }),
part('reason', { valueCode: 'no_institutional_model' }),
],
}),
],
),
),
);
expect(g.models).toEqual([]);
expect(g.withoutModel).toEqual(['no_institutional_model']);
});
});
+615
View File
@@ -0,0 +1,615 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, input } from '@angular/core';
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',
missing_data: 'Falta un dato clínico',
history_not_demonstrable: 'Antecedente no demostrable',
not_applicable: 'Escenario no aplicable',
contradictory: 'Resultados contradictorios',
ambiguous: 'Escenario ambiguo',
scenario_not_implemented: 'Escenario aún no resuelto',
unverifiable_correspondence: 'Correspondencia no verificable',
no_published_row: 'Sin fila publicada para esta combinación',
};
/** Why a resolution or a comparison has no value. */
export const REASON_TEXT: Record<string, string> = {
no_cytology_reported_by_cutoff: 'No hay citología con resultado a la fecha de corte.',
sample_not_reported_by_cutoff: 'La citología pedida no tenía resultado a la fecha de corte.',
no_birth_date: 'Falta la fecha de nacimiento.',
age_outside_25_65: 'La edad está fuera del rango de las tablas (25 a 65 años).',
cytology_not_in_tables: 'El resultado citológico no está en las tablas.',
missing_hpv: 'La citología no tiene resultado de VPH.',
contradictory_hpv: 'El VPH es negativo pero se reporta un genotipo positivo.',
hpv_positive_row:
'Las tablas muestran «VPH positivo» junto a VPH 16 y VPH 18; no se verificó si esa fila es el total o los otros tipos, y no se asume.',
no_earlier_test_registered:
'La plataforma no tiene una prueba anterior con VPH; no demuestra que no haya antecedente.',
earlier_test_older_than_5_years: 'La prueba anterior es de hace más de 5 años.',
colposcopy_or_treatment_before:
'Hay una colposcopía, biopsia o tratamiento previo: es un escenario posterior a colposcopía o tratamiento, aún no resuelto.',
history_is_a_surveillance_scenario:
'El antecedente anormal corresponde a la tabla de vigilancia, aún no resuelta.',
registered_cin2_plus_before: 'Hay un CIN2+ registrado antes: las tablas lo excluyen.',
hysterectomy_declared: 'El formulario declara una histerectomía: las tablas la excluyen.',
procedure_after_without_named_referral:
'Hay una colposcopía o biopsia posterior, pero ningún registro la nombra como derivada de esta citología (una asociación por fechas no basta).',
several_biopsies_name_the_cytology: 'Varias biopsias nombran esta citología.',
not_a_referral_result_in_the_tables:
'La citología no es un resultado de derivación de las tablas.',
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.',
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.',
outcome_differs: 'El desenlace del modelo no es el de la tabla (CIN3+).',
unknown_model: 'El desenlace del modelo no está registrado para comparar.',
horizon_not_published_by_model: 'El modelo no publica una predicción a este horizonte.',
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.',
};
const KEY_TEXT: Record<string, string> = {
history: 'Antecedente más reciente',
hpv: 'VPH actual',
cytology: 'Citología actual',
referral: 'Resultado de tamizaje que originó la colposcopía',
biopsy: 'Resultado de biopsia',
};
const USED_TEXT: Record<string, string> = {
'sample-date': 'toma',
'report-date': 'reporte',
'request-date': 'solicitud',
result: 'resultado',
hpv: 'VPH',
'hpv-16': 'VPH 16',
'hpv-18': 'VPH 18',
histology: 'histología',
};
const usedValue = (v: unknown) => (v === true ? 'positivo' : v === false ? 'negativo' : String(v));
export interface ComparisonView {
model?: string;
title?: string;
outcome?: string;
/** probabilities, 0 to 1 */
institutional?: number;
low?: number;
high?: number;
status: string;
/** percentage points, institutional minus reference */
differencePp?: number;
reasons: string[];
}
export interface HorizonView {
years: number;
label: string;
published: boolean;
/** probability, 0 to 1; none when the tables leave it blank */
reference?: number;
comparisons: ComparisonView[];
}
export interface ReferenceView {
status: string;
reasons: string[];
cutoff?: string;
scenario?: { label: string; keys: { name: string; value: string }[] };
index?: { sampleDate?: string; reportDate?: string; result?: string; age?: number };
evaluationDate?: string;
source?: { id?: string; file?: string; sha256?: string; outcome?: string; status?: string };
row?: { sheet?: string; number?: number; officialCheck?: string; matchedVia?: string };
used: { label: string; details: string }[];
assumptions: string[];
horizons: HorizonView[];
}
type Part = ParametersParameter;
const value = (p?: Part) =>
p?.valueCode ??
p?.valueString ??
p?.valueDate ??
p?.valueInteger ??
p?.valueDecimal ??
p?.valueBoolean ??
undefined;
const named = (parts: Part[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const one = (parts: Part[] | undefined, name: string) => value(named(parts, name)[0]);
/** The horizon's name; the colposcopy table's one year is a year, never "immediate". */
export function horizonLabel(years: number): string {
return years === 0 ? 'Inmediato (al índice)' : years === 1 ? '1 año' : `${years} años`;
}
/** The result of `$reference-risk` as the section shows it. A value absent from the answer stays
* absent: no zero is made of a blank, and no difference is made of a comparison that is not one. */
export function referenceView(answer: Parameters): ReferenceView {
const top = answer.parameter ?? [];
const scenario = named(top, 'scenario')[0];
const index = named(top, 'index')[0]?.part;
const row = named(top, 'row')[0]?.part;
const source = named(top, 'source')[0]?.part;
const view: ReferenceView = {
status: String(one(top, 'status') ?? 'missing_data'),
reasons: named(top, 'reason').map((r) => String(value(r))),
cutoff: one(top, 'cutoff') as string | undefined,
evaluationDate: one(top, 'evaluation-date') as string | undefined,
used: named(top, 'used').map((u) => ({
label: String(one(u.part, 'label') ?? ''),
details: (u.part ?? [])
.filter((p) => p.name !== 'label')
.map((p) => `${USED_TEXT[p.name ?? ''] ?? p.name}: ${usedValue(value(p))}`)
.join(' · '),
})),
assumptions: named(top, 'assumption').map((a) => String(value(a))),
horizons: named(top, 'horizon').map((h) => {
const years = Number(one(h.part, 'years'));
return {
years,
label: horizonLabel(years),
published: one(h.part, 'published') === true,
reference: one(h.part, 'reference') as number | undefined,
comparisons: named(h.part, 'comparison').map((c) => ({
model: one(c.part, 'model') as string | undefined,
title: one(c.part, 'title') as string | undefined,
outcome: one(c.part, 'outcome') as string | undefined,
institutional: one(c.part, 'institutional') as number | undefined,
low: one(c.part, 'institutional-low') as number | undefined,
high: one(c.part, 'institutional-high') as number | undefined,
status: String(one(c.part, 'status')),
differencePp: one(c.part, 'difference-pp') as number | undefined,
reasons: named(c.part, 'reason').map((r) => String(value(r))),
})),
};
}),
};
if (scenario?.part)
view.scenario = {
label: String(one(scenario.part, 'label') ?? ''),
keys: named(scenario.part, 'key').map((k) => ({
name: KEY_TEXT[String(one(k.part, 'name'))] ?? String(one(k.part, 'name')),
value: String(one(k.part, 'value')),
})),
};
if (index)
view.index = {
sampleDate: one(index, 'sample-date') as string | undefined,
reportDate: one(index, 'report-date') as string | undefined,
result: one(index, 'result') as string | undefined,
age: one(index, 'age') as number | undefined,
};
if (row)
view.row = {
sheet: one(row, 'sheet') as string | undefined,
number: one(row, 'number') as number | undefined,
officialCheck: one(row, 'official-check') as string | undefined,
matchedVia: one(row, 'matched-via') as string | undefined,
};
if (source)
view.source = {
id: one(source, 'id') as string | undefined,
file: one(source, 'file') as string | undefined,
sha256: one(source, 'sha256') as string | undefined,
outcome: one(source, 'outcome') as string | undefined,
status: one(source, 'status') as string | undefined,
};
return view;
}
/** Outcome names as the screens say them; presentation only: the API's identifiers stay as they are
* (an outcome this map does not know is shown as the API gave it). */
export const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3 o más grave (CIN3+)',
'CIN2+': 'CIN2 o más grave (CIN2+)',
cancer: 'Cáncer',
'CIN2+ within one year': 'CIN2+ en un año',
'not stated as a histology outcome': 'No expresado como desenlace histológico',
};
export const outcomeText = (outcome?: string) => (outcome ? (OUTCOME_TEXT[outcome] ?? outcome) : '');
export interface ModelRow extends Omit<ComparisonView, 'reasons'> {
years: number;
label: string;
/** the reasons of this horizon that its model's other horizons do not share */
reasons: string[];
}
export interface ModelBlock {
model?: string;
title?: string;
outcome?: string;
/** reasons shared by every non-comparable horizon of this model, said once */
reasons: string[];
rows: ModelRow[];
}
export interface Grouped {
/** the reference by horizon: one table, whatever the models */
reference: { years: number; label: string; published: boolean; reference?: number }[];
/** reasons shared by every non-comparable comparison of every model, said once */
common: string[];
models: ModelBlock[];
/** no institutional model evaluated her: said once, with its reasons */
withoutModel: string[];
}
const shared = (lists: string[][]) =>
lists.length > 1 ? lists[0].filter((r) => lists.every((l) => l.includes(r))) : [];
/** Groups only what is equivalent: the reference once per horizon; a reason that every non-comparable
* comparison of a model (or of all models) gives, once; everything else stays where it is. Nothing is
* dropped, and a difference is never made: it is only the API's, on a comparable row. */
export function groupReference(v: ReferenceView): Grouped {
const reference = v.horizons.map((h) => ({
years: h.years,
label: h.label,
published: h.published,
reference: h.reference,
}));
const byModel = new Map<string, ModelBlock>();
const withoutModel: string[] = [];
for (const h of v.horizons)
for (const c of h.comparisons) {
if (!c.model) {
for (const r of c.reasons) if (!withoutModel.includes(r)) withoutModel.push(r);
continue;
}
const block = byModel.get(c.model) ?? {
model: c.model,
title: c.title,
outcome: c.outcome,
reasons: [],
rows: [],
};
byModel.set(c.model, block);
block.rows.push({ ...c, years: h.years, label: h.label });
}
const models = [...byModel.values()];
const notComparable = (b: ModelBlock) => b.rows.filter((r) => r.status !== 'comparable');
const common = shared(models.flatMap(notComparable).map((r) => r.reasons));
const everyModel = models.length > 1 ? common : [];
for (const b of models) {
const own = shared(notComparable(b).map((r) => r.reasons.filter((x) => !everyModel.includes(x))));
b.reasons = own;
for (const r of b.rows)
if (r.status !== 'comparable')
r.reasons = r.reasons.filter((x) => !everyModel.includes(x) && !own.includes(x));
}
return { reference, common: everyModel, models, withoutModel };
}
const OFFICIAL: Record<string, string> = {
match: 'coincide con la tabla del NCI',
'match_within_0.01': 'coincide con la tabla del NCI salvo 0.01 puntos de redondeo',
differs: 'no coincide con la tabla del NCI',
not_found_in_official: 'sin fila equivalente en la tabla del NCI consultada',
blank_in_both: 'en blanco en ambas',
no_official_file: 'sin tabla del NCI para cotejar',
};
/** Comparison with the NCI's reference risks (experimental): the reference by horizon beside the
* institutional models', the difference only where the two are the same estimate. */
@Component({
selector: 'app-reference-risk',
imports: [DecimalPipe],
template: `
@let v = view();
<section
class="reference"
data-section="referencia-nci"
aria-label="Comparación de riesgos de referencia"
>
<h3>Comparación de riesgos de referencia</h3>
<dl class="meta">
<div>
<dt>Estado</dt>
<dd [attr.data-status]="v.status">{{ statusText(v.status) }}</dd>
</div>
@if (v.scenario; as s) {
<div>
<dt>Escenario clínico</dt>
<dd>{{ s.label }}</dd>
</div>
}
@if (v.source?.outcome; as out) {
<div>
<dt>Desenlace de la referencia</dt>
<dd [attr.data-outcome]="out">{{ outcomeText(out) }}</dd>
</div>
}
@if (v.evaluationDate ?? v.index?.sampleDate; as day) {
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ day }}</dd>
</div>
}
@if (v.cutoff) {
<div>
<dt>Fecha de corte</dt>
<dd>{{ v.cutoff }}</dd>
</div>
}
@if (v.source; as src) {
<div>
<dt>Fuente y versión</dt>
<dd>Tablas NCI (libro {{ src.file }}, {{ src.id }}); no validadas</dd>
</div>
}
</dl>
@if (v.reasons.length) {
<ul class="why" aria-label="Motivo">
@for (r of v.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (v.horizons.length) {
@let g = grouped();
<table class="plain" aria-label="Referencia NCI por horizonte">
<thead>
<tr>
<th>Horizonte</th>
<th>Referencia NCI</th>
</tr>
</thead>
<tbody>
@for (h of g.reference; track h.years) {
<tr [attr.data-years]="h.years">
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
<td class="nowrap" data-label="Referencia NCI">
@if (h.reference !== undefined) {
<strong>{{ h.reference * 100 | number: '1.2-2' }} %</strong>
} @else {
<span>No publicado</span>
}
</td>
</tr>
}
</tbody>
</table>
<h4>Modelos institucionales</h4>
@if (g.withoutModel.length || !g.models.length) {
<p class="nomodel">
<strong>No disponible</strong>
</p>
<ul class="why" aria-label="Motivo">
@for (r of g.withoutModel; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@if (g.common.length) {
<p class="muted">Motivos que comparten todas las comparaciones no válidas:</p>
<ul class="why" aria-label="Motivos comunes">
@for (r of g.common; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
@for (m of g.models; track m.model) {
<section class="model" [attr.data-model]="m.model" [attr.aria-label]="m.title">
<h5>
{{ m.title }}
<span class="muted" [attr.data-outcome]="m.outcome">{{ outcomeText(m.outcome) }}</span>
</h5>
@if (m.reasons.length) {
<p class="muted">No comparable en estos horizontes:</p>
<ul class="why" aria-label="Motivos del modelo">
@for (r of m.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
<table class="plain" [attr.aria-label]="'Comparación de ' + m.title">
<thead>
<tr>
<th>Horizonte</th>
<th>Modelo institucional</th>
<th>Diferencia (puntos porcentuales)</th>
</tr>
</thead>
<tbody>
@for (c of m.rows; track c.years) {
<tr [attr.data-years]="c.years">
<td class="nowrap" data-label="Horizonte">{{ c.label }}</td>
<td data-label="Modelo institucional">
@if (c.institutional !== undefined) {
{{ c.institutional * 100 | number: '1.2-2' }} %
@if (c.low !== undefined && c.high !== undefined) {
<span class="muted"
>(IC 95 %: {{ c.low * 100 | number: '1.2-2' }}–{{
c.high * 100 | number: '1.2-2'
}}
%)</span
>
}
} @else {
<span>No disponible</span>
}
</td>
<td data-label="Diferencia (puntos porcentuales)">
@if (c.status === 'comparable' && c.differencePp !== undefined) {
<strong
>{{ c.differencePp > 0 ? '+' : ''
}}{{ c.differencePp | number: '1.2-2' }}</strong
>
} @else {
<span>No comparable</span>
@if (c.reasons.length) {
<ul class="why">
@for (r of c.reasons; track r) {
<li>{{ reasonText(r) }}</li>
}
</ul>
}
}
</td>
</tr>
}
</tbody>
</table>
</section>
}
<p class="muted note">
La diferencia es el riesgo institucional menos el riesgo NCI y solo se calcula si ambos
estiman lo mismo (desenlace, horizonte, fecha índice y población verificados).
</p>
}
@if (v.used.length || v.assumptions.length || v.scenario || v.row) {
<details class="used">
<summary>Antecedentes utilizados</summary>
@if (v.scenario; as s) {
<ul>
@for (k of s.keys; track k.name) {
<li>{{ k.name }}: {{ k.value }}</li>
}
</ul>
}
@if (v.index; as i) {
<p>
Citología evaluada: toma {{ i.sampleDate }}, reporte {{ i.reportDate }}, resultado
{{ i.result }}
@if (i.age !== undefined) {
, edad {{ i.age }} años
}
.
</p>
}
<ul>
@for (u of v.used; track $index) {
<li>
<strong>{{ u.label }}</strong>: {{ u.details }}
</li>
}
</ul>
@if (v.row; as r) {
<p class="muted">
Fila de origen: «{{ r.sheet }}», fila {{ r.number }}
@if (r.matchedVia === 'table_group') {
(categoría agrupada definida por la propia tabla)
}
— {{ official(r.officialCheck) }}.
</p>
}
@for (a of v.assumptions; track a) {
<p class="muted">Sin verificar: {{ a }}</p>
}
</details>
}
</section>
`,
styles: `
.reference {
border: 1px dashed #9aa3ab;
border-radius: 6px;
margin: 16px 0;
padding: 12px 16px;
}
h3 {
margin: 0 0 8px;
}
.meta {
display: flex;
flex-wrap: wrap;
gap: 8px 24px;
margin: 0 0 8px;
}
.meta dt {
color: var(--color-text-secondary);
font-size: 12px;
}
.meta dd {
font-weight: 500;
margin: 0;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th,
td {
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
.model {
border-top: 1px solid #dce3e7;
margin-top: 8px;
padding-top: 4px;
}
h4,
h5 {
margin: 12px 0 4px;
}
h5 .muted {
font-weight: 400;
margin-left: 8px;
}
.why {
margin: 4px 0;
padding-left: 18px;
}
.note {
font-size: 12px;
}
.used {
margin-top: 8px;
}
.used summary {
cursor: pointer;
}
@media (max-width: 700px) {
.reference {
padding: 8px 10px;
}
table,
thead,
tbody,
tr,
th,
td {
display: block;
}
thead {
display: none;
}
tr {
border-bottom: 1px solid #dce3e7;
padding: 6px 0;
}
td {
padding: 2px 0;
}
td::before {
color: var(--color-text-secondary);
content: attr(data-label);
display: block;
font-size: 12px;
}
}
`,
})
export class ReferenceRisk {
readonly view = input.required<ReferenceView>();
protected readonly grouped = computed(() => groupReference(this.view()));
protected outcomeText(outcome?: string) {
return outcomeText(outcome);
}
protected statusText(status: string) {
return STATUS_TEXT[status] ?? status;
}
protected reasonText(reason: string) {
return REASON_TEXT[reason] ?? reason;
}
protected official(check?: string) {
return OFFICIAL[check ?? ''] ?? 'sin cotejo';
}
}
+100
View File
@@ -0,0 +1,100 @@
import { curveFigure, curveText } from './risk-curve';
const model = (text: string, predictions: object[], index = '2026-06-01') => ({
text,
index,
predictions: predictions as { years: number; p: number; low?: number; high?: number }[],
});
const traces = (models: ReturnType<typeof model>[]) => curveFigure(models, 0.4).data as any[];
describe('the institutional curves', () => {
it('draws one series per model, named as the model, at the horizons it publishes only', () => {
const found = traces([
model('Riesgo LIEAG+ v3', [
{ years: 1, p: 0.08 },
{ years: 3, p: 0.21 },
{ years: 5, p: 0.34 },
]),
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[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
expect(lines[1].mode).toBe('markers');
expect(lines[0].color ?? lines[0].line.color).not.toBe(lines[1].line.color);
});
it('puts the axis ticks on the published horizons and invents none between them', () => {
const f = curveFigure(
[
model('M v1', [
{ years: 0, p: 0.01 },
{ years: 5, p: 0.05 },
]),
],
0.05,
);
expect((f.layout!.xaxis as any).tickvals).toEqual([0, 5]);
expect((f.layout!.xaxis as any).title.text).toBe(
'Horizonte (años desde la fecha índice (2026-06-01))',
);
const mixed = curveFigure(
[model('A v1', [{ years: 1, p: 0.1 }]), model('B v1', [{ years: 3, p: 0.2 }], '2026-07-01')],
0.2,
);
expect((mixed.layout!.xaxis as any).tickvals).toEqual([1, 3]);
expect((mixed.layout!.xaxis as any).title.text).toBe('Horizonte (años desde la fecha índice)'); // two index dates: none is named
});
it('draws a band only where intervals are published, with its own legend entry, and no band without them', () => {
const none = traces([
model('Sin IC v1', [
{ years: 1, p: 0.1 },
{ years: 5, p: 0.3 },
]),
]);
expect(none).toHaveLength(1);
expect(none[0].fill).toBeUndefined();
const withBand = traces([
model('Con IC v1', [
{ years: 1, p: 0.1, low: 0.05, high: 0.12 },
{ years: 3, p: 0.2, low: 0.15, high: 0.28 },
{ years: 5, p: 0.3, low: 0.26, high: 0.44 },
]),
]);
expect(withBand.map((t) => t.name)).toEqual([undefined, 'IC 95 % Con IC', 'Con IC']);
expect(withBand[1].fill).toBe('tonexty');
expect(withBand[1].y.map((y: number) => Math.round(y))).toEqual([5, 15, 26]);
});
it('a horizon without an interval is a gap in the band, never filled with the probability', () => {
const [high, low] = traces([
model('Hueco v1', [
{ years: 1, p: 0.1, low: 0.05, high: 0.12 },
{ years: 3, p: 0.2 },
{ years: 5, p: 0.3, low: 0.26, high: 0.44 },
]),
]);
expect(high.y[1]).toBeNull();
expect(low.y[1]).toBeNull();
expect(low.connectgaps).toBe(false);
});
it('one published interval is an error bar, not a band', () => {
const found = traces([model('Uno v1', [{ years: 5, p: 0.34, low: 0.26, high: 0.44 }])]);
expect(found).toHaveLength(1);
expect(found[0].error_y.array[0]).toBeCloseTo(10);
expect(found[0].error_y.arrayminus[0]).toBeCloseTo(8);
});
it('says each model, its index date and every horizon it publishes, with intervals only where there are', () => {
expect(
curveText([
model('Riesgo LIEAG+ v3', [
{ years: 5, p: 0.34, low: 0.26, high: 0.44 },
{ years: 1, p: 0.08 },
]),
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 %).',
]);
});
});
+126
View File
@@ -0,0 +1,126 @@
import { Figure, PALETTE } from '../plot';
export interface CurvePrediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface CurveModel {
/** the model's own title, with its version */
text: string;
/** the model's index date */
index: string;
predictions: CurvePrediction[];
}
const percent = (n: number) =>
(Math.round(n * 1000) / 10).toLocaleString('es-MX', { minimumFractionDigits: 1 });
const title = (m: CurveModel) => m.text.replace(/ v\d+$/, '');
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
* publishes (a model with one horizon is a point), its 95 % interval as a band where it publishes
* one at two or more horizons and as an error bar at a single one. No horizon, interval or
* probability is made up: between published horizons the line joins them and nothing else. The
* NCI reference is not here. */
export function curveFigure(models: CurveModel[], top: number): Figure {
const shown = models.filter((m) => m.predictions.length);
const years = [...new Set(shown.flatMap((m) => m.predictions.map((p) => p.years)))].sort(
(a, b) => a - b,
);
const dates = [...new Set(shown.map((m) => m.index))];
return {
data: shown.flatMap((m, i) => {
const color = PALETTE[i % PALETTE.length];
const sorted = [...m.predictions].sort((a, b) => a.years - b.years);
const x = sorted.map((p) => p.years);
const name = title(m);
const bounded = sorted.filter(interval);
const traces: object[] = [];
if (bounded.length > 1) {
// a gap in the published intervals stays a gap: nothing is drawn between them
const at = (pick: (p: CurvePrediction) => number | undefined) =>
sorted.map((p) => (interval(p) ? (pick(p) as number) * 100 : null));
traces.push(
{
x,
y: at((p) => p.high),
mode: 'lines',
line: { width: 0 },
connectgaps: false,
showlegend: false,
hoverinfo: 'skip',
legendgroup: name,
},
{
x,
y: at((p) => p.low),
mode: 'lines',
line: { width: 0 },
fill: 'tonexty',
connectgaps: false,
fillcolor: color + '33',
name: `IC 95 % ${name}`,
legendgroup: name,
hoverinfo: 'skip',
},
);
}
traces.push({
x,
y: sorted.map((p) => p.p * 100),
mode: sorted.length > 1 ? 'lines+markers' : 'markers',
name,
legendgroup: name,
line: { color },
marker: { color, size: 8 },
...(bounded.length === 1
? {
error_y: {
type: 'data',
symmetric: false,
color,
array: sorted.map((p) => (interval(p) ? (p.high! - p.p) * 100 : 0)),
arrayminus: sorted.map((p) => (interval(p) ? (p.p - p.low!) * 100 : 0)),
},
}
: {}),
hovertemplate: `${name}<br>%{x} años: %{y:.2f} %<extra></extra>`,
});
return traces;
}) as Figure['data'],
layout: {
xaxis: {
title: {
text: `Horizonte (años desde la fecha índice${dates.length === 1 ? ` (${dates[0]})` : ''})`,
},
tickmode: 'array',
tickvals: years,
ticktext: years.map(String),
},
// At least 0–5 %: a near-zero risk reads as near zero, not as a full axis.
yaxis: {
title: { text: 'Probabilidad (%)' },
range: [0, Math.max(5, top * 110)],
tickformat: '.0f',
},
},
} as Figure;
}
/** The curves in words: each model, its index date and every horizon it publishes, with its
* interval where it has one. */
export function curveText(models: CurveModel[]): string[] {
return models
.filter((m) => m.predictions.length)
.map((m) => {
const sorted = [...m.predictions].sort((a, b) => a.years - b.years);
const said = sorted.map(
(p) =>
`${p.years === 0 ? 'al índice' : `${p.years} ${p.years === 1 ? 'año' : 'años'}`}: ${percent(p.p)} %` +
(interval(p) ? ` (IC 95 %: ${percent(p.low!)}–${percent(p.high!)} %)` : ''),
);
return `${title(m)} (fecha índice ${m.index}): ${said.join('; ')}.`;
});
}
+86
View File
@@ -0,0 +1,86 @@
import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
describe('the risk scales', () => {
it('keeps zero as a value, and a missing horizon as none', () => {
expect(horizon([at(0, 0), at(5, 0.5)], 0)).toMatchObject({ p: 0 });
expect(horizon([at(5, 0.5)], 0)).toBeUndefined(); // never taken from another horizon
expect(horizon([at(0, 0.02)], 5)).toBeUndefined();
expect(horizon([], 5)).toBeUndefined();
});
it('reads 0, 2, 50, 98 and 100 % as they are', () => {
for (const p of [0, 0.02, 0.5, 0.98, 1]) expect(horizon([at(5, p)], 5)?.p).toBe(p);
});
it('a value outside 0 to 1 is not a prediction; an interval needs both ends inside 0 to 1', () => {
expect(horizon([at(5, 1.2)], 5)).toBeUndefined();
expect(horizon([at(5, -0.1)], 5)).toBeUndefined();
expect(horizon([at(5, Number.NaN)], 5)).toBeUndefined();
expect(horizon([at(5, 0.4, 0.3, 0.5)], 5)).toMatchObject({ low: 0.3, high: 0.5 });
expect(horizon([at(5, 0.4, 0.3)], 5)).toMatchObject({
p: 0.4,
low: undefined,
high: undefined,
});
expect(horizon([at(5, 0.4, 0.6, 0.5)], 5)?.low).toBeUndefined();
expect(horizon([at(5, 0.4, -0.1, 0.5)], 5)?.low).toBeUndefined();
});
it('draws both horizons of every model, each model with its own title and index day', () => {
const groups = riskGroups([
{
text: 'Supervivencia v3',
index: '2026-02-01',
predictions: [at(0, 0), at(5, 0.5, 0.4, 0.6)],
},
{ text: 'Recurrencia v2', index: '2026-03-01', predictions: [at(5, 0.98)] },
{ text: 'Otro', index: '2026-03-02', predictions: [at(3, 0.3)] }, // no horizon of its own
]);
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'];
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]);
expect(groups[2].scales.map((s) => s.risk)).toEqual([undefined, undefined]);
});
it('with no model, both horizons are drawn unavailable', () => {
const [none, ...rest] = riskGroups([]);
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],
]);
});
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',
]);
});
});
describe('which models feed the risk scales', () => {
it('excludes survival and recurrence estimates, which are not risks of the scales outcome', () => {
expect(['cacu.cin2_pim', 'cacu.cancer_pim', 'cacu.cin2_logistic'].every(isRiskModel)).toBe(
true,
);
expect(isRiskModel('cacu.survival')).toBe(false);
expect(isRiskModel('cama.recurrence')).toBe(false);
});
it('with no risk model both horizons are unavailable (nothing is converted from a survival)', () => {
const risk = [
{
text: 'm',
index: '2026-01-01',
predictions: [{ years: 5, p: 0.7 }],
model: 'cacu.survival',
},
].filter((m) => isRiskModel(m.model));
expect(riskGroups(risk).flatMap((g) => g.scales.map((s) => s.risk))).toEqual([
undefined,
undefined,
]);
});
});
+176 -32
View File
@@ -12,6 +12,11 @@ export interface RiskScale {
risk?: Prediction;
}
/** Whether a model's estimate is a risk of the outcome the scales and curves draw. Survival (S(t)) and
* recurrence-free survival are estimates of another outcome, shown in their own analysis: they are
* never drawn on these scales, and no conversion (1 − S) is made. */
export const isRiskModel = (model: string) => !/.(survival|recurrence)$/.test(model);
/** Each model's risk at its index visit and at five years; none where it gives no such horizon. */
export function riskScales(models: { text: string; predictions: Prediction[] }[]): RiskScale[] {
return models.flatMap((m) =>
@@ -22,54 +27,193 @@ export function riskScales(models: { text: string; predictions: Prediction[] }[]
);
}
const unit = (n?: number): n is number => typeof n === 'number' && n >= 0 && n <= 1;
/** A model's published prediction at one horizon, when it is a probability: zero is a real value,
* a missing horizon is none (never taken from another horizon), a value outside 0 to 1 is none. */
export function horizon(predictions: Prediction[], years: number): Prediction | undefined {
const found = predictions.find((p) => p.years === years);
if (!found || !unit(found.p)) return undefined;
const interval = unit(found.low) && unit(found.high) && found.low <= found.high;
return {
...found,
low: interval ? found.low : undefined,
high: interval ? found.high : undefined,
};
}
/** One model's two horizons, each with its prediction or none. */
export interface RiskGroup {
/** the model's own title and the day it was scored (none: no model has scored her) */
title?: string;
scenario?: string;
index?: string;
scales: { label: string; risk?: Prediction }[];
}
const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo 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 };
}
/** The scales the page draws: both horizons of every model, or, with no model, both horizons
* unavailable. */
export function riskGroups(
models: { text: string; index: string; predictions: Prediction[] }[],
): RiskGroup[] {
const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
return models.length
? models.map((m) => ({
...titleParts(m.text),
index: m.index,
scales: scales(m.predictions),
}))
: [{ scales: scales([]) }];
}
/** Segmented scales of 0 to 100 %. The four equal parts are numeric and descriptive: they do not
* stand for clinical thresholds. Without a prediction the bar is neutral grey, says it is not
* available and has no marker. */
@Component({
selector: 'app-risk-scales',
imports: [DecimalPipe],
template: `
@for (s of scales(); track s.label) {
<div class="scale">
<span>{{ s.label }}</span>
<div class="line">
@if (s.risk; as r) {
<span class="mark" [style.left.%]="r.p * 100"></span>
}
@if (groups().length) {
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
}
@for (g of groups(); track $index) {
@if (g.title) {
<h3>{{ g.title }}</h3>
}
@for (s of g.scales; track s.label) {
<div class="risk-scale" [attr.data-scale]="s.label">
<p>
<strong>{{ s.label }}</strong>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
· IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high * 100 | number: '1.1-2' }}
%
}
} @else {
· No disponible
}
</p>
<div class="risk-plot" [class.unavailable]="!s.risk">
<div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) {
<span
class="risk-interval"
[style.left.%]="r.low * 100"
[style.width.%]="(r.high - r.low) * 100"
aria-hidden="true"
></span>
}
<span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
<strong
class="risk-value"
[style.left]="'clamp(2.5rem, ' + r.p * 100 + '%, calc(100% - 2.5rem))'"
>{{ r.p * 100 | number: '1.1-2' }} %</strong
>
}
</div>
<div class="risk-labels" aria-hidden="true">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span>
</div>
</div>
@if (s.risk; as r) {
<strong>{{ r.p * 100 | number: '1.1-2' }} %</strong>
@if (r.low !== undefined) {
<span>
IC 95 %: {{ r.low * 100 | number: '1.1-2' }}–{{ r.high! * 100 | number: '1.1-2' }} %
</span>
}
} @else {
<strong>No disponible</strong>
}
</div>
}
@if (g.index) {
<p class="muted foot">
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p>
}
}
`,
styles: `
.scale {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 8px;
.note {
margin: 0 0 8px;
}
.line {
background: linear-gradient(to right, #a8c243, #c24269);
flex: 1 1 200px;
height: 8px;
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
}
.risk-scale p {
margin: 0;
}
.risk-plot {
padding-top: 30px;
position: relative;
}
.mark {
background: #333;
.risk-line {
background: linear-gradient(
to right,
#42a77e 0 25%,
#a8c243 25% 50%,
#df8640 50% 75%,
#c24269 75% 100%
);
height: 16px;
}
.unavailable .risk-line {
background: repeating-linear-gradient(
to right,
#d9dfe2 0,
#d9dfe2 calc(25% - 1px),
#fff calc(25% - 1px),
#fff 25%
);
}
.risk-interval {
border-left: 2px solid #17324d;
border-right: 2px solid #17324d;
height: 8px;
min-width: 2px;
position: absolute;
top: -4px;
top: 20px;
}
.risk-interval::before {
background: #17324d;
content: '';
height: 2px;
left: 0;
position: absolute;
right: 0;
top: 3px;
}
.foot {
font-size: 12px;
}
.risk-marker {
background: #17324d;
bottom: -2px;
height: 20px;
position: absolute;
transform: translateX(-50%);
width: 3px;
}
.risk-value {
color: #17324d;
font-size: 13px;
position: absolute;
top: 1px;
transform: translateX(-50%);
white-space: nowrap;
}
.risk-labels {
display: flex;
font-size: 12px;
justify-content: space-between;
margin-top: 3px;
}
`,
})
export class RiskScales {
readonly scales = input.required<RiskScale[]>();
readonly groups = input.required<RiskGroup[]>();
}
+29
View File
@@ -0,0 +1,29 @@
import { parseSeries, seriesName } from './risk-series';
describe('risk series', () => {
it('reads each series and keeps an absent interval absent', () => {
const [series] = parseSeries({
resourceType: 'Parameters',
parameter: [
{
name: 'series',
part: [
{ name: 'id', valueString: 'cacu.cin2_pim' },
{ name: 'source', valueString: 'Institucional' },
{ name: 'outcome', valueString: 'CIN2+' },
{ name: 'status', valueCode: 'resolved' },
{
name: 'point',
part: [
{ name: 'years', valueInteger: 0 },
{ name: 'probability', valueDecimal: 0 },
],
},
],
},
],
});
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('Institucional · LIEAG+ (CIN2+)');
});
});
+205
View File
@@ -0,0 +1,205 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, input, signal } from '@angular/core';
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 { Plot } from '../plot';
import { curveFigure } from './risk-curve';
import { REASON_TEXT } from './reference-risk';
export interface SeriesPoint {
years: number;
p: number;
low?: number;
high?: number;
}
/** One series of `$risk-series`: a source, an outcome and her variables. */
export interface Series {
id: string;
source: string;
outcome: string;
label: string;
resolved: boolean;
reasons: string[];
assumptions: string[];
points: SeriesPoint[];
}
const OUTCOME_TEXT: Record<string, string> = {
'CIN2+': 'LIEAG+ (CIN2+)',
'CIN3+': 'CIN3+',
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}`;
/** The series of the answer. A value absent from it stays absent. */
export function parseSeries(answer: Parameters): Series[] {
const all = (parts: ParametersParameter[] | undefined, name: string) =>
(parts ?? []).filter((p) => p.name === name);
const one = (parts: ParametersParameter[] | undefined, name: string) => all(parts, name)[0];
return all(answer.parameter, 'series').map(({ part }) => ({
id: one(part, 'id')?.valueString ?? '',
source: one(part, 'source')?.valueString ?? '',
outcome: one(part, 'outcome')?.valueString ?? '',
label: one(part, 'label')?.valueString ?? '',
resolved: one(part, 'status')?.valueCode === 'resolved',
reasons: all(part, 'reason').map((r) => r.valueCode ?? ''),
assumptions: all(part, 'assumption').map((a) => a.valueString ?? ''),
points: all(part, 'point').map(({ part: at }) => ({
years: one(at, 'years')?.valueInteger ?? 0,
p: one(at, 'probability')?.valueDecimal ?? 0,
low: one(at, 'low')?.valueDecimal,
high: one(at, 'high')?.valueDecimal,
})),
}));
}
/** The chosen series as bars at one horizon and as curves. Series are shown side by side; no
* difference between them is computed. */
@Component({
selector: 'app-risk-series',
imports: [DecimalPipe, MatCheckboxModule, MatFormFieldModule, MatSelectModule, Plot],
template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
<div class="choices">
@for (s of available(); track s.id) {
<mat-checkbox [checked]="chosen().has(s.id)" (change)="toggle(s.id)">
{{ name(s) }}
</mat-checkbox>
}
</div>
@if (selected().length) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Horizonte</mat-label>
<mat-select [value]="horizon()" (selectionChange)="picked.set($event.value)">
@for (h of horizons(); track h) {
<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) {
<p class="muted">{{ name(s) }}: no disponible. {{ why(s) }}</p>
}
`,
styles: `
:host {
display: block;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 0 16px;
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 {
readonly series = input.required<Series[]>();
protected readonly name = seriesName;
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) */
private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed(
() =>
new Set(
this.available()
.filter((s) => (s.source === 'Institucional') !== this.toggled().has(s.id))
.map((s) => s.id),
),
);
protected readonly selected = computed(() =>
this.available().filter((s) => this.chosen().has(s.id)),
);
protected readonly horizons = computed(() =>
[...new Set(this.selected().flatMap((s) => s.points.map((p) => p.years)))].sort(
(a, b) => a - b,
),
);
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(() => {
const shown = this.selected().map((s) => ({
model: s.id,
text: seriesName(s),
index: '',
predictions: s.points,
}));
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
const figure = curveFigure(shown, top);
// sources do not share an index date: the axis says only the horizon
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
return figure;
});
protected toggle(id: string) {
const next = new Set(this.toggled());
if (!next.delete(id)) next.add(id);
this.toggled.set(next);
}
protected why(s: Series) {
return s.reasons.map((r) => REASONS[r] ?? r).join(' ');
}
}
+101 -1
View File
@@ -1,5 +1,5 @@
import { EXT } from '../fhir';
import { route } from './stages';
import { between, interval, route } from './stages';
const ext = (name: string, value: object) => ({ url: EXT + name, ...value });
const cytology = (...extension: object[]): any => ({ effectiveDateTime: '2026-01-10', extension });
@@ -24,3 +24,103 @@ describe('the route of a cytology', () => {
expect(states('2026-01-15').slice(2)).toEqual(['unknown', 'unknown', 'unknown']);
});
});
describe('the days between stages', () => {
it('counts whole days and says nothing for a missing or out-of-order day', () => {
expect(between('2026-01-10', '2026-02-01')).toBe(22);
expect(between('2026-01-10', '2026-01-10')).toBe(0);
expect(between(undefined, '2026-02-01')).toBeUndefined();
expect(between('2026-02-01', '2026-01-10')).toBeUndefined();
});
it('writes a dash, never a zero, for a missing day, and marks an interval that rests on an inference', () => {
expect(interval(undefined, '2026-02-01')).toBe('—');
expect(interval('2026-01-10', undefined)).toBe('—');
expect(interval('2026-01-10', '2026-01-11')).toBe('1 día');
expect(interval('2026-01-10', '2026-02-01')).toBe('22 días');
expect(interval('2026-01-10', '2026-02-01', true)).toBe('22 días (inferido)');
});
it('knows an ambiguous stage the backend does not publish yet', () => {
const report = cytology(ext('colposcopy-date', { valueDate: '2026-02-01' }));
expect(route(report, '2026-12-31').map((s) => s.state)).not.toContain('ambiguous');
});
});
describe('the route by what the backend says of each stage', () => {
const full = (...more: object[]) =>
cytology(
ext('report-date', { valueDate: '2026-01-20' }),
ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('stage-colposcopy-state', { valueCode: 'inferred' }),
ext('stage-colposcopy-source', { valueCode: 'clinical-note' }),
ext('stage-colposcopy-source', { valueCode: 'biopsy-order' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-date', { valueDate: '2026-03-01' }),
ext('biopsy-link', { valueCode: 'recorded' }),
ext('stage-biopsy-state', { valueCode: 'recorded' }),
ext('stage-biopsy-source', { valueCode: 'biopsy-record' }),
ext('diagnosis-date', { valueDate: '2026-03-10' }),
ext('stage-diagnosis-state', { valueCode: 'inferred' }),
ext('stage-diagnosis-source', { valueCode: 'clinical-note' }),
...more,
);
it('carries the state and every source of each stage, and the form for the first two', () => {
const stages = route(full(), '2026-12-31');
expect(stages.map((s) => s.state)).toEqual([
'recorded',
'recorded',
'inferred',
'recorded',
'inferred',
]);
expect(stages.map((s) => s.sources)).toEqual([
['cytology-form'],
['cytology-form'],
['clinical-note', 'biopsy-order'],
['biopsy-record'],
['clinical-note'],
]);
});
it("an ambiguous or pending state is the backend's, and a source it does not know is dropped", () => {
const ambiguous = full().extension!.map((e: any) =>
e.url.endsWith('stage-biopsy-state') ? { ...e, valueCode: 'ambiguous' } : e,
);
expect(route({ ...full(), extension: ambiguous }, '2026-12-31')[3].state).toBe('ambiguous');
const odd = full(ext('stage-diagnosis-source', { valueCode: 'something-new' }));
expect(route(odd, '2026-12-31')[4].sources).toEqual(['clinical-note']);
const pending = cytology(
ext('stage-biopsy-state', { valueCode: 'pending' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-link', { valueCode: 'inferred' }),
ext('stage-biopsy-source', { valueCode: 'date-association' }),
);
const biopsy = route(pending, '2026-12-31')[3];
expect(biopsy).toMatchObject({
state: 'pending',
requested: '2026-02-01',
sources: ['date-association'],
});
expect(biopsy.day).toBeUndefined();
});
it('by a cut-off before a stage its state is not known, and one before the report is pending', () => {
const early = route(full(), '2026-01-25');
expect(early.slice(2).map((s) => s.state)).toEqual(['unknown', 'unknown', 'unknown']);
expect(early.slice(2).map((s) => s.sources)).toEqual([undefined, undefined, undefined]);
const between = route(full(), '2026-02-15')[3];
expect(between).toMatchObject({ state: 'pending', requested: '2026-02-01' });
});
it('a request with no biopsy day and no pending state is not read as pending when the backend speaks', () => {
// reported outside the route's horizon: the backend gives the request and no biopsy state
const outside = cytology(
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('stage-colposcopy-state', { valueCode: 'inferred' }),
);
expect(route(outside, '2026-12-31')[3].state).toBe('unknown');
// a report with no state extensions: the request alone reads as pending
const older = cytology(ext('biopsy-request-date', { valueDate: '2026-02-01' }));
expect(route(older, '2026-12-31')[3].state).toBe('pending');
});
it('an ambiguous stage rests no interval on its day', () => {
expect(interval(undefined, '2026-03-01')).toBe('—');
});
});
+193 -47
View File
@@ -1,39 +1,84 @@
import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4';
import { ext } from '../fhir';
import { EXT, ext } from '../fhir';
/** A step of the route that a cytology starts. A day with no state is unknown. */
/** A step of the route that a cytology starts. A day with no state is unknown. `ambiguous` is how
* the page would draw a step the backend flagged as ambiguous; the current contract never does. */
export interface Stage {
label: string;
day?: string;
state: 'recorded' | 'inferred' | 'pending' | 'unknown';
state: 'recorded' | 'inferred' | 'pending' | 'ambiguous' | 'unknown';
/** where the stage's day comes from, as the backend says it (see `SOURCES`); none: not said */
sources?: string[];
/** what a stage without a day knows: a biopsy requested on this day */
requested?: string;
}
/** Where a stage's day comes from. */
export const SOURCES: Record<string, string> = {
'cytology-form': 'Formulario de citología',
'clinical-note': 'Nota clínica',
'biopsy-order': 'Orden de biopsia',
'biopsy-record': 'Registro de la biopsia (nombra la citología)',
'date-association': 'Asociación por fechas',
};
export const STATES: Record<Stage['state'], string> = {
recorded: 'Registrada',
inferred: 'Inferida por fechas',
pending: 'Pendiente',
ambiguous: 'Ambigua',
unknown: 'Sin dato',
};
/** The route of one cytology, as its report says it, by `cutoff`. */
/** The route of one cytology, as its report says it, by `cutoff`. The backend says each later
* stage's state and sources (`stage-<name>-state`, `stage-<name>-source`); a report without them
* is read from its days and the biopsy link. */
export function route(cytology: DiagnosticReport | undefined, cutoff: string): Stage[] {
const by = (day?: string) => (day && day.slice(0, 10) <= cutoff ? day.slice(0, 10) : undefined);
const at = (name: string) => by(ext(cytology, name)?.valueDate);
const step = (label: string, day: string | undefined, known: Stage['state']): Stage => ({
const said = (k: string) => ext(cytology, `stage-${k}-state`)?.valueCode;
const published = ['colposcopy', 'biopsy', 'diagnosis'].some((k) => said(k));
const from = (k: string) =>
(cytology?.extension ?? [])
.filter((e) => e.url === EXT + `stage-${k}-source`)
.map((e) => e.valueCode!)
.filter((c) => c in SOURCES);
const KNOWN: Stage['state'][] = ['recorded', 'inferred', 'pending', 'ambiguous'];
/** A stage's state by what the backend says (or, with nothing said, by `otherwise`). */
const later = (
label: string,
k: string,
day: string | undefined,
otherwise: Stage['state'],
): Stage => {
const state = said(k) as Stage['state'] | undefined;
const found = state && KNOWN.includes(state) && state !== 'pending' ? state : otherwise;
return { label, day, state: day ? found : 'unknown', sources: day ? from(k) : undefined };
};
const day = (label: string, d: string | undefined, sources: string[]): Stage => ({
label,
day,
state: day ? known : 'unknown',
day: d,
state: d ? 'recorded' : 'unknown',
sources: d ? sources : undefined,
});
const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded' ? 'recorded' : 'inferred';
const biopsy = step('Reporte de biopsia', at('biopsy-date'), linked);
if (!biopsy.day && at('biopsy-request-date')) biopsy.state = 'pending';
const biopsy = later('Reporte de biopsia', 'biopsy', at('biopsy-date'), linked);
const requested = at('biopsy-request-date');
const reportedAfter = !!ext(cytology, 'biopsy-date')?.valueDate && !biopsy.day;
// asked by the cut-off and not reported by it: pending (the backend's pending, or a report after the
// cut-off); a report with no states at all reads a request with no day as pending
if (!biopsy.day && requested && (reportedAfter || said('biopsy') === 'pending' || !published)) {
biopsy.state = 'pending';
biopsy.requested = requested;
biopsy.sources = from('biopsy');
}
return [
step('Toma de muestra', by(cytology?.effectiveDateTime), 'recorded'),
step('Resultado de citología', at('report-date'), 'recorded'),
step('Colposcopía', at('colposcopy-date'), 'inferred'),
day('Toma de muestra', by(cytology?.effectiveDateTime), ['cytology-form']),
day('Resultado de citología', at('report-date'), ['cytology-form']),
later('Colposcopía', 'colposcopy', at('colposcopy-date'), 'inferred'),
biopsy,
step('Diagnóstico', at('diagnosis-date'), 'inferred'),
later('Diagnóstico', 'diagnosis', at('diagnosis-date'), 'inferred'),
];
}
@@ -43,32 +88,46 @@ export function between(from?: string, to?: string): number | undefined {
return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);
}
/** The stages as a line of dots; `detail` adds each one's state, day and days elapsed. */
/** Days between two stages as text: "—" for a missing day (never a zero), and "(inferido)" when the
* interval rests on a stage that is only inferred from dates. */
export function interval(from?: string, to?: string, inferred = false): string {
const days = between(from, to);
return days === undefined
? '—'
: `${days} ${days === 1 ? 'día' : 'días'}${inferred ? ' (inferido)' : ''}`;
}
/** The stages as a line of nodes joined by a line; `detail` adds each one's state, day and the
* days elapsed since the previous stage and since the sample. */
@Component({
selector: 'app-stages',
template: `
<ol [class.detail]="detail()">
<ol [class.detail]="detail()" [attr.aria-label]="summary()">
@for (s of shown(); track s.label) {
<li [title]="s.label + ': ' + s.text">
<span class="dot" [class]="s.state"></span>
<li [title]="s.title">
<span class="node" [class]="s.state"></span>
@if (detail()) {
<strong>{{ s.label }}</strong>
<span>{{ s.text }}</span>
@if (s.day) {
<span>{{ s.day }}</span>
}
@if (s.previous !== undefined) {
<span>{{ s.previous }} días desde la etapa anterior</span>
}
@if (s.sample !== undefined) {
<span>{{ s.sample }} días desde la toma</span>
}
<div class="info">
<strong>{{ s.label }}</strong>
<span>{{ s.text }}</span>
<span>{{
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
}}</span>
@if (s.origin && s.origin !== 'Formulario de citología') {
<span class="origin">Procedencia: {{ s.origin }}</span>
}
<span class="interval">Desde anterior: {{ s.previous }}</span>
<span class="interval">Desde toma: {{ s.sample }}</span>
</div>
}
</li>
}
</ol>
`,
styles: `
:host {
display: block;
}
ol {
display: flex;
gap: 6px;
@@ -76,33 +135,110 @@ export function between(from?: string, to?: string): number | undefined {
margin: 0;
padding: 0;
}
ol.detail {
flex-wrap: wrap;
gap: 16px;
li {
position: relative;
}
.detail li {
display: flex;
flex: 1 1 120px;
flex-direction: column;
font-size: 0.85rem;
}
.dot {
border: 2px solid #9aa3ab;
/* the states: recorded is solid green, inferred double blue, pending a pale solid, ambiguous a
double rose border, and what has no data a dashed empty circle */
.node {
background: #fff;
border: 2px dashed #667b8a;
border-radius: 50%;
display: inline-block;
box-sizing: border-box;
display: block;
height: 12px;
position: relative;
width: 12px;
z-index: 1;
}
.recorded {
background: #6a8000;
border-color: #6a8000;
background: #387b66;
border-style: solid;
}
.inferred {
background: #a8c243;
border-color: #6a8000;
background: #4269a0;
border-style: double;
}
.pending {
border-color: #c24269;
background: #fff1c9;
border-style: solid;
}
.ambiguous {
border-color: #a84460;
border-style: double;
}
/* the detail: one column per stage across the whole width, the nodes joined by a line */
ol.detail {
background: #fff;
border: 1px solid #dce3e7;
border-radius: 8px;
gap: 0;
padding: 18px 12px;
}
.detail li {
flex: 1;
min-width: 0;
text-align: center;
}
.detail .node {
height: 18px;
margin: 0 auto;
width: 18px;
}
.detail li:not(:last-child)::after {
border-top: 1px solid #667b8a;
content: '';
left: calc(50% + 9px);
position: absolute;
right: calc(-50% + 9px);
top: 9px;
}
.info {
color: #60717d;
display: flex;
flex-direction: column;
font-size: 12px;
gap: 3px;
overflow-wrap: anywhere;
padding: 8px 4px 0;
}
.info strong {
color: #243d4b;
}
.interval {
color: #365b69;
font-weight: 600;
}
.origin {
font-style: italic;
}
@media (max-width: 700px) {
ol.detail {
display: block;
}
.detail li {
display: flex;
gap: 12px;
padding-bottom: 10px;
text-align: left;
}
.detail li:not(:last-child)::after {
border-left: 1px solid #667b8a;
border-top: 0;
bottom: 0;
left: 9px;
right: auto;
top: 18px;
}
.detail .node {
flex: none;
margin: 0;
}
.info {
padding: 0;
}
}
`,
})
@@ -111,11 +247,21 @@ export class Stages {
readonly detail = input(false);
protected readonly shown = computed(() => {
const all = this.stages();
const inferred = (s?: Stage) => s?.state === 'inferred';
// an ambiguous stage has a day the backend does not stand behind: no interval rests on it
const day = (s?: Stage) => (s?.state === 'ambiguous' ? undefined : s?.day);
return all.map((s, i) => ({
...s,
text: STATES[s.state],
previous: i ? between(all[i - 1].day, s.day) : undefined,
sample: i > 1 ? between(all[0].day, s.day) : undefined,
title: `${s.label}: ${STATES[s.state]}`,
origin: (s.sources ?? []).map((c) => SOURCES[c]).join(' · '),
previous: i ? interval(day(all[i - 1]), day(s), inferred(s) || inferred(all[i - 1])) : '—',
sample: interval(day(all[0]), day(s), inferred(s)),
}));
});
protected readonly summary = computed(() =>
this.shown()
.map((s) => s.title)
.join('; '),
);
}
+102
View File
@@ -0,0 +1,102 @@
import { scenarioFigure } from '../gobernanza/figures';
import { insufficientText, sortUndrawn } from './survival-scenarios';
const base = (over: object = {}) => ({
km: {
months: [0, 12, 24, 36],
S: [1, 0.9, 0.8, 0.7],
low: [1, 0.8, 0.7, 0.55],
high: [1, 0.95, 0.9, 0.82],
},
weibull: { t: [0, 36], S: [1, 0.7] },
weibull_fractional: { t: [0, 36], S: [1, 0.72] },
points: { COMB: { S: [0.9, 0.7], low: [0.8, 0.55], high: [0.95, 0.82] } },
...over,
});
const draw = (e: object) => scenarioFigure('t', e, [12, 36], 'S(t)').figure.data as any[];
const bands = (d: any[]) => d.filter((t) => t.fill === 'toself');
const model = (d: any[]) => d.find((t) => t.name?.startsWith('LR + HBN'));
describe('survival curves with absent values', () => {
it('complete data draw one band and symmetric-free error bars, as before', () => {
const d = draw(base());
expect(bands(d).length).toBe(1);
expect(bands(d)[0].x.length).toBe(8);
expect(model(d).error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.05, 0.12]);
expect(model(d).error_y.arrayminus.map((v: number) => +v.toFixed(2))).toEqual([0.1, 0.15]);
});
it('a band is drawn only where both limits exist, never from an absent one', () => {
const km = {
months: [0, 12, 24, 36, 48],
S: [1, 0.9, 0.8, 0.7, 0.6],
low: [1, 0.8, null, 0.55, 0.4],
high: [1, 0.95, null, 0.82, 0.7],
};
const d = draw(base({ km }));
expect(bands(d).map((b) => b.x.length)).toEqual([4, 4]); // [0,12] and [36,48]; each polygon out and back
for (const b of bands(d)) expect(b.y.every((v: unknown) => typeof v === 'number')).toBe(true);
const none = draw(
base({
km: { ...km, low: [null, null, null, null, null], high: [null, null, null, null, null] },
}),
);
expect(bands(none).length).toBe(0); // no limits: no band at all
expect(none.find((t) => t.name?.startsWith('Kaplan')).y).toEqual([1, 0.9, 0.8, 0.7, 0.6]); // the curve stays
});
it('a point without its limits has no bar; zero is a value and unavailable is not drawn', () => {
const d = draw(
base({ points: { COMB: { S: [0, null], low: [null, null], high: [null, null] } } }),
);
const m = model(d);
expect(m.y).toEqual([0, null]); // 0 % is drawn at 0, an absent value is a gap
expect(m.error_y).toBeUndefined(); // no invented limits
expect(model(draw(base({ points: { COMB: { S: [0, null] } } }))).error_y).toBeUndefined();
const half = model(
draw(base({ points: { COMB: { S: [0.9, 0.7], low: [0.8, null], high: [0.95, null] } } })),
);
expect(half.error_y.array).toEqual([expect.closeTo(0.05, 5), null]);
expect(half.error_y.arrayminus).toEqual([expect.closeTo(0.1, 5), null]);
});
});
describe('scenarios without a curve', () => {
const report = {
escenarios_sin_curvas: [
{ escenario: 'VPH negativo', n: 9, fallecidos: 2 },
{ escenario: 'Citología · ASC-H', n: 0, fallecidos: 0 },
],
min_fallecidos_escenario: 5,
};
it('those the report lists as lacking deaths keep its numbers and the minimum', () => {
expect(sortUndrawn(report, ['VPH negativo', 'Citología · ASC-H']).insufficient).toEqual([
{ name: 'VPH negativo', n: 9, deaths: 2, minimum: 5 },
{ name: 'Citología · ASC-H', n: 0, deaths: 0, minimum: 5 }, // zero deaths is a count, not a gap
]);
});
it('one the report does not mention is absent, never "insufficient"', () => {
expect(sortUndrawn(report, ['VPH negativo', 'Edad · 45-54']).missing).toEqual(['Edad · 45-54']);
expect(sortUndrawn({}, ['a'])).toEqual({ insufficient: [], missing: ['a'] });
expect(sortUndrawn(null, ['a'])).toEqual({ insufficient: [], missing: ['a'] });
expect(sortUndrawn({ escenarios_sin_curvas: 'x' }, ['a']).missing).toEqual(['a']);
});
it('a listing without counts is still insufficient, without inventing numbers', () => {
expect(
sortUndrawn({ escenarios_sin_curvas: [{ escenario: 'a' }] }, ['a']).insufficient,
).toEqual([{ name: 'a', n: undefined, deaths: undefined, minimum: undefined }]);
});
});
describe('the insufficient-data text', () => {
it("says the report's numbers and leaves out the ones it did not give", () => {
expect(insufficientText({ name: 'a', n: 9, deaths: 2, minimum: 5 })).toBe(
'Datos insuficientes para trazar la curva (n = 9, fallecidos = 2; mínimo requerido: 5 fallecidos).',
);
expect(insufficientText({ name: 'a', n: 0, deaths: 0 })).toBe(
'Datos insuficientes para trazar la curva (n = 0, fallecidos = 0).',
);
expect(insufficientText({ name: 'a', n: null, deaths: 0, minimum: 5 })).toBe(
'Datos insuficientes para trazar la curva (fallecidos = 0; mínimo requerido: 5 fallecidos).',
);
expect(insufficientText({ name: 'a' })).toBe('Datos insuficientes para trazar la curva.');
});
});
+51
View File
@@ -0,0 +1,51 @@
/** A scenario the report says has too few deaths for a curve, with its counts and the minimum. */
export interface Insufficient {
name: string;
n?: number | null;
deaths?: number | null;
minimum?: number;
}
/** Her scenarios without a curve, apart: those the report lists as lacking deaths (with the numbers it
* gives) and those it does not mention at all. */
export function sortUndrawn(
report: Record<string, unknown> | null | undefined,
undrawn: string[],
): { insufficient: Insufficient[]; missing: string[] } {
const listed = (
Array.isArray(report?.['escenarios_sin_curvas']) ? report['escenarios_sin_curvas'] : []
) as {
escenario?: string;
n?: number | null;
fallecidos?: number | null;
}[];
const minimum =
typeof report?.['min_fallecidos_escenario'] === 'number'
? report['min_fallecidos_escenario']
: undefined;
const insufficient: Insufficient[] = [];
const missing: string[] = [];
for (const name of undrawn) {
const found = listed.find((s) => s.escenario === name);
if (found) insufficient.push({ name, n: found.n, deaths: found.fallecidos, minimum });
else missing.push(name);
}
return { insufficient, missing };
}
/** What the section says of a scenario the report lists as lacking deaths; the numbers are the
* report's and a missing one is left out, never replaced. */
export function insufficientText(u: Insufficient): string {
const fmt = (v: number) => v.toLocaleString('es-MX');
const counts = [
typeof u.n === 'number' ? `n = ${fmt(u.n)}` : '',
typeof u.deaths === 'number' ? `fallecidos = ${fmt(u.deaths)}` : '',
]
.filter(Boolean)
.join(', ');
const details = [
counts,
u.minimum !== undefined ? `mínimo requerido: ${fmt(u.minimum)} fallecidos` : '',
].filter(Boolean);
return `Datos insuficientes para trazar la curva${details.length ? ` (${details.join('; ')})` : ''}.`;
}
+1
View File
@@ -28,6 +28,7 @@ type Entity = Rejection['entity'];
type Row = Record<string, unknown>;
const ENTITIES: Record<Entity, string> = {
cacu_eligibility_evidence: 'Evidencia de elegibilidad CaCu',
cervical_cytology: 'Citología cervical',
cervical_biopsy: 'Biopsia cervical',
clinical_note: 'Nota médica',