CaCu record: stages with states and sources, segmented risk scales, antecedents and collapsible findings

This commit is contained in:
Angel Capetillo Zavala
2026-12-01 17:15:10 -06:00
parent e1e8da6093
commit 8fc06038fb
12 changed files with 1519 additions and 108 deletions
+627
View File
@@ -0,0 +1,627 @@
import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
// The individual record of CaCu: the stages inside "Historial médico" and the risk scales.
// "(simulado)" tests rewrite the API's answers in the browser to cover what the synthetic data
// do not hold (every stage state, every risk value); they show how the page draws them, not the backend.
const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
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);
});
/** The record of the first patient of the risk list, as an address. */
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const link = page.locator('table.worklist tbody tr a').first();
await link.waitFor({ timeout: 120_000 });
const url = (await link.getAttribute('href'))!;
return { url, sample: new URL(url, 'http://x').searchParams.get('citologia')! };
}
const plus = (day: string, days: number) =>
new Date(Date.parse(day) + days * 86_400_000).toISOString().slice(0, 10);
type Route = Partial<
Record<'report' | 'colposcopy' | 'request' | 'biopsy' | 'diagnosis', number>
> & {
link?: 'recorded';
/** more extensions on the report, as the backend would publish them (stage states and sources) */
extra?: object[];
};
/** The shown cytology's report carries these dates (days after its sample). */
async function withRoute(page: Page, sample: string, days: Route) {
await page.route('**/api/cacu/fhir/DiagnosticReport**', async (route) => {
const response = await route.fetch();
const body = await response.json();
for (const { resource: r } of body.entry ?? []) {
if (r.code?.coding?.[0]?.code !== 'cervical_cytology' || r.effectiveDateTime !== sample)
continue;
const names = {
report: 'report-date',
colposcopy: 'colposcopy-date',
request: 'biopsy-request-date',
biopsy: 'biopsy-date',
diagnosis: 'diagnosis-date',
} as const;
r.extension = (r.extension ?? []).filter(
(e: any) =>
!Object.values(names).some((n) => e.url === EXT + n) && e.url !== EXT + 'biopsy-link',
);
for (const [key, name] of Object.entries(names)) {
const d = days[key as keyof typeof names];
if (d !== undefined) r.extension.push({ url: EXT + name, valueDate: plus(sample, d) });
}
if (days.link) r.extension.push({ url: EXT + 'biopsy-link', valueCode: days.link });
r.extension.push(...(days.extra ?? []));
}
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
}
type Prediction = [years: number, p: number, low?: number, high?: number];
const risk = (
id: string,
text: string,
model: string,
index: string,
predictions: Prediction[],
) => ({
resourceType: 'RiskAssessment',
id,
status: 'final',
method: { text, coding: [{ code: model }] },
occurrenceDateTime: index,
prediction: predictions.map(([years, p, low, high]) => ({
whenRange: { high: { value: years, unit: 'a', code: 'a' } },
probabilityDecimal: p,
extension:
low === undefined
? []
: [
{ url: EXT + 'ic-bajo', valueDecimal: low },
{ url: EXT + 'ic-alto', valueDecimal: high },
],
})),
});
/** The patient has these risk assessments. */
async function withRisks(page: Page, assessments: object[]) {
await page.route('**/api/cacu/fhir/RiskAssessment**', (route) =>
route.fulfill({
contentType: 'application/fhir+json',
body: JSON.stringify({
resourceType: 'Bundle',
type: 'searchset',
entry: assessments.map((resource) => ({ resource })),
}),
}),
);
}
const historial = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Historial médico' }),
});
const scale = (page: Page, label: string, nth = 0) =>
page.locator(`.risk-scale[data-scale="${label}"]`).nth(nth);
const IMMEDIATE = 'Riesgo inmediato (al índice)';
const FIVE = 'Riesgo a 5 años';
async function open(page: Page, url: string) {
await page.goto(url);
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
}
/** Where a scale draws its marker, in % of the bar, and the figure it prints. */
async function drawn(scaleBox: Locator) {
const marker = scaleBox.locator('.risk-marker');
return {
markers: await marker.count(),
left: (await marker.count())
? await marker.evaluate((e) => (e as HTMLElement).style.left)
: undefined,
value: (await scaleBox.locator('.risk-value').count())
? (await scaleBox.locator('.risk-value').innerText()).trim()
: undefined,
grey: await scaleBox.locator('.risk-plot.unavailable').count(),
};
}
test('ficha: the five stages are a line of nodes inside "Historial médico", with the export button', async ({
page,
}) => {
const { url } = await firstRecord(page);
await open(page, url);
await expect(page.locator('mat-card-title', { hasText: 'Etapas del tamizaje' })).toHaveCount(0);
const stages = historial(page).locator('[data-section=etapas] app-stages li');
await expect(stages).toHaveCount(5);
// one row: the five nodes are level
const tops = await stages
.locator('.node')
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
expect(new Set(tops).size).toBe(1);
// each stage says its name, state, day and both intervals, centred
const first = stages.first();
await expect(first).toContainText('Toma de muestra');
await expect(first).toContainText('Registrada');
await expect(first).toContainText('Desde anterior: —');
await expect(first).toContainText('Desde toma: 0 días');
expect(
await first.locator('.info').evaluate((e) => getComputedStyle(e.parentElement!).textAlign),
).toBe('center');
await expect(historial(page)).toContainText('a la fecha de corte');
await expect(historial(page).getByRole('button', { name: 'Exportar PDF' })).toBeVisible();
// history and tests keep their tables
await expect(historial(page).getByRole('table')).toBeVisible();
await expect(page.locator('mat-card-title', { hasText: 'Pruebas y resultados' })).toBeVisible();
});
test('ficha: the export of the record still downloads its PDF', async ({ page }) => {
const { url } = await firstRecord(page);
await open(page, url);
const saved = page.waitForEvent('download');
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
expect((await saved).suggestedFilename()).toBe('expediente-cacu.pdf');
});
test('ficha: with no model both horizons are drawn grey, not available, without a marker', async ({
page,
}) => {
const { url } = await firstRecord(page);
await open(page, url);
for (const label of [IMMEDIATE, FIVE]) {
const box = scale(page, label);
await expect(box).toContainText('No disponible');
expect(await drawn(box)).toMatchObject({ markers: 0, grey: 1 });
await expect(box.locator('.risk-labels span')).toHaveText([
'0 %',
'25 %',
'50 %',
'75 %',
'100 %',
]);
}
await expect(
page.getByText('Divisiones numéricas descriptivas; no representan umbrales clínicos.'),
).toBeVisible();
});
test('ficha (simulado): every state of a stage, its dates and its intervals', async ({ page }) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
link: 'recorded',
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const stages = historial(page).locator('app-stages li');
const text = async (n: number) => (await stages.nth(n).innerText()).replace(/\s+/g, ' ');
expect(await text(0)).toContain(`Registrada ${sample}`);
expect(await text(1)).toContain(
`Registrada ${plus(sample, 14)} Procedencia: Formulario de citología Desde anterior: 14 días Desde toma: 14 días`,
);
// colposcopy and diagnosis are inferred from dates: their intervals say so
expect(await text(2)).toContain(
`Inferida por fechas ${plus(sample, 30)} Desde anterior: 16 días (inferido) Desde toma: 30 días (inferido)`,
);
// a recorded biopsy link is recorded; the interval since an inferred stage is still inferred
expect(await text(3)).toContain(
`Registrada ${plus(sample, 50)} Desde anterior: 20 días (inferido) Desde toma: 50 días`,
);
expect(await text(4)).toContain(
`Inferida por fechas ${plus(sample, 70)} Desde anterior: 20 días (inferido)`,
);
const state = (n: number) =>
stages
.nth(n)
.locator('.node')
.evaluate(
(e) => getComputedStyle(e).backgroundColor + '|' + getComputedStyle(e).borderTopStyle,
);
expect(await state(0)).toBe('rgb(56, 123, 102)|solid'); // recorded
expect(await state(2)).toBe('rgb(66, 105, 160)|double'); // inferred
// an inferred biopsy link: inferred as well
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
expect(await text(3)).toContain('Inferida por fechas');
});
test('ficha (simulado): the cut-off hides what is dated after it; a biopsy asked and not reported is pending', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
});
const cutoff = plus(sample, 45); // after the request, before the report
await open(page, `${url.split('?')[0]}?corte=${cutoff}&citologia=${sample}`);
const stages = historial(page).locator('app-stages li');
const states = await stages.locator('.info span:nth-child(2)').allInnerTexts();
expect(states.map((s) => s.trim())).toEqual([
'Registrada',
'Registrada',
'Inferida por fechas',
'Pendiente',
'Sin dato',
]);
await expect(historial(page)).toContainText(`a la fecha de corte ${cutoff}`);
const pending = await stages
.nth(3)
.locator('.node')
.evaluate((e) => getComputedStyle(e).backgroundColor);
expect(pending).toBe('rgb(255, 241, 201)');
const unknown = await stages
.nth(4)
.locator('.node')
.evaluate((e) => getComputedStyle(e).borderTopStyle);
expect(unknown).toBe('dashed');
await expect(stages.nth(4)).toContainText('Sin fecha');
await expect(stages.nth(4)).toContainText('Desde toma: —');
// a cut-off before the sample: nothing is known
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
await withRoute(page, sample, { report: 14 });
await open(page, `${url.split('?')[0]}?corte=${plus(sample, -1)}&citologia=${sample}`);
expect(
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
).toEqual(Array(5).fill('Sin dato'));
});
test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tell zero from absent', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
[0, 0],
[5, 0.5, 0.4, 0.6],
]),
risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [
[0, 0.02, 0.01, 0.03],
[5, 0.98, 0.95, 1],
]),
risk('c', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]), // no immediate horizon
risk('d', 'Parcial v1', 'cacu.partial', '2026-05-01', [[0, 0.5]]), // no five-year horizon
]);
await open(page, url);
await expect(
page.getByRole('heading', { name: 'Supervivencia v3 · fecha índice 2026-02-01' }),
).toBeVisible();
await expect(
page.getByRole('heading', { name: 'Recurrencia v2 · fecha índice 2026-03-01' }),
).toBeVisible();
const at = async (label: string, nth: number) => drawn(scale(page, label, nth));
// group order follows the page's models: survival, recurrence, other, partial
const groups = await page.locator('.risk-scale').count();
expect(groups).toBe(8); // both horizons of four models
const model = async (n: number) => [await at(IMMEDIATE, n), await at(FIVE, n)];
const [survival, recurrence, other, partial] = [
await model(0),
await model(1),
await model(2),
await model(3),
];
expect(survival[0]).toMatchObject({ markers: 1, left: '0%', value: '0.0 %', grey: 0 }); // a real zero
expect(survival[1]).toMatchObject({ left: '50%', value: '50.0 %' });
expect(recurrence[0]).toMatchObject({ left: '2%', value: '2.0 %' });
expect(recurrence[1]).toMatchObject({ left: '98%', value: '98.0 %' });
expect(other[0]).toMatchObject({ markers: 0, grey: 1 }); // absent, not zero
expect(other[1]).toMatchObject({ left: '100%', value: '100.0 %' });
expect(partial[0]).toMatchObject({ left: '50%' });
expect(partial[1]).toMatchObject({ markers: 0, grey: 1 });
await expect(scale(page, IMMEDIATE, 2)).toContainText('No disponible');
await expect(scale(page, FIVE, 3)).toContainText('No disponible');
await expect(scale(page, FIVE, 0)).toContainText('IC 95 %: 40.0–60.0 %');
await expect(scale(page, FIVE, 1)).toContainText('IC 95 %: 95.0–100.0 %');
await expect(scale(page, IMMEDIATE, 0)).not.toContainText('IC 95 %'); // none published, none invented
// the descriptive note stays, and the model table and curve of rebuild are still there
await expect(page.getByText('no representan umbrales clínicos')).toBeVisible();
await expect(page.getByRole('columnheader', { name: 'Probabilidad', exact: true })).toBeVisible();
});
test('ficha (simulado): the scale is drawn in four equal segments with the numeric divisions', async ({
page,
}) => {
const { url } = await firstRecord(page);
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
]);
await open(page, url);
const box = scale(page, FIVE);
await expect(box.locator('.risk-labels span')).toHaveText([
'0 %',
'25 %',
'50 %',
'75 %',
'100 %',
]);
const line = await box.locator('.risk-line').evaluate((e) => getComputedStyle(e).backgroundImage);
for (const colour of [
'rgb(66, 167, 126)',
'rgb(168, 194, 67)',
'rgb(223, 134, 64)',
'rgb(194, 66, 105)',
])
expect(line).toContain(colour);
// the marker sits at 50 % of the bar
const [bar, mark] = await Promise.all([
box.locator('.risk-plot').boundingBox(),
box.locator('.risk-marker').boundingBox(),
]);
expect(Math.abs(mark!.x + mark!.width / 2 - (bar!.x + bar!.width / 2))).toBeLessThan(3);
});
for (const width of [1440, 480]) {
test(`ficha (simulado) at ${width} px: the stages and the scales lay out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
link: 'recorded',
});
await withRisks(page, [
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
[0, 0],
[5, 0.98, 0.95, 1],
]),
risk('b', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]),
]);
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
await page.waitForTimeout(800);
expect(await layoutProblems(page)).toEqual([]);
const tops = await historial(page)
.locator('app-stages li .node')
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
// wide: one row of nodes; narrow: a column (each below the previous)
if (width > 700) expect(new Set(tops).size).toBe(1);
else {
expect(tops).toEqual([...tops].sort((a, b) => a - b));
expect(new Set(tops).size).toBe(5);
}
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
});
}
const code = (name: string, valueCode: string) => ({ url: EXT + name, valueCode });
const nodeOf = (page: Page, n: number) => historial(page).locator('app-stages li').nth(n);
/** A record, by the API, whose cytology (the latest of the first patients) satisfies `wanted`. */
async function recordWhere(page: Page, wanted: (report: any) => boolean) {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
const ids: string[] = patients.entry.map((e: any) => e.resource.id);
for (let i = 0; i < ids.length; i += 25) {
const subject = ids
.slice(i, i + 25)
.map((p) => 'Patient/' + p)
.join(',');
const found = await (
await page.request.get(`/api/cacu/fhir/DiagnosticReport?_count=200&subject=${subject}`)
).json();
for (const { resource: r } of found.entry ?? [])
if (r.code?.coding?.[0]?.code === 'cervical_cytology' && wanted(r))
return {
id: r.subject.reference.split('/')[1] as string,
sample: r.effectiveDateTime as string,
};
}
throw new Error('no record with those stages in the first patients');
}
const has = (r: any, name: string) => (r.extension ?? []).some((e: any) => e.url === EXT + name);
test('ficha: the stages say what the backend demonstrates, with their sources', async ({
page,
}) => {
const { id, sample } = await recordWhere(
page,
(r) => has(r, 'stage-colposcopy-state') && has(r, 'stage-biopsy-state'),
);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const states = await historial(page)
.locator('app-stages li .info span:nth-child(2)')
.allInnerTexts();
expect(states[0]).toBe('Registrada');
expect(states[2]).toBe('Inferida por fechas'); // colposcopy is always inferred
expect(['Inferida por fechas', 'Registrada']).toContain(states[3]);
const colposcopy = (await nodeOf(page, 2).innerText()).replace(/\s+/g, ' ');
expect(colposcopy).toMatch(/Procedencia: (Nota clínica|Orden de biopsia)/);
expect(colposcopy).toContain('Desde anterior:');
expect((await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ')).toMatch(
/Procedencia: (Asociación por fechas|Registro de la biopsia)/,
);
// the first two stages come from the form
expect(await nodeOf(page, 0).innerText()).toContain('Procedencia: Formulario de citología');
});
test('ficha (simulado): a stage the backend flags as ambiguous is drawn so, with no interval resting on it', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
biopsy: 50,
diagnosis: 70,
extra: [
code('stage-biopsy-state', 'ambiguous'),
code('stage-biopsy-source', 'date-association'),
code('stage-colposcopy-state', 'inferred'),
code('stage-colposcopy-source', 'clinical-note'),
code('stage-colposcopy-source', 'biopsy-order'),
],
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
expect(biopsy).toContain(`Ambigua ${plus(sample, 50)}`);
expect(biopsy).toContain('Procedencia: Asociación por fechas');
expect(biopsy).toContain('Desde anterior: — Desde toma: —');
expect(
await nodeOf(page, 3)
.locator('.node')
.evaluate((e) => getComputedStyle(e).borderTopStyle),
).toBe('double');
// no interval rests on the ambiguous day, so the next stage has none from the previous one either
expect((await nodeOf(page, 4).innerText()).replace(/\s+/g, ' ')).toContain('Desde anterior: —');
// a colposcopy dated by a note and a biopsy order lists both sources
expect(await nodeOf(page, 2).innerText()).toContain(
'Procedencia: Nota clínica · Orden de biopsia',
);
});
test('ficha (simulado): a biopsy the backend says is pending shows its request, not a day', async ({
page,
}) => {
const { url, sample } = await firstRecord(page);
await withRoute(page, sample, {
report: 14,
colposcopy: 30,
request: 40,
extra: [
code('stage-biopsy-state', 'pending'),
code('stage-biopsy-source', 'date-association'),
code('biopsy-link', 'inferred'),
],
});
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
expect(biopsy).toContain('Pendiente');
expect(biopsy).toContain(`Solicitada el ${plus(sample, 40)}`);
expect(biopsy).toContain('Desde toma: —');
// colposcopy and diagnosis are never pending: no request is known for them
expect(
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
).not.toContain('Pendiente' + 'x');
const states = (
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts()
).map((t) => t.trim());
expect(states.filter((t) => t === 'Pendiente')).toHaveLength(1);
});
// ---- the record's tests and its antecedents
const antecedents = (page: Page) => page.locator('[data-section=antecedentes]');
const tests = (page: Page) =>
page.locator('mat-card', {
has: page.locator('mat-card-title', { hasText: 'Pruebas y resultados' }),
});
test('ficha: antecedents and gynecologic evaluation have their own section; tests keep their results', async ({
page,
}) => {
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const card = antecedents(page);
await expect(card).toBeVisible();
await expect(card).toContainText('no son diagnósticos confirmados');
await expect(card).toContainText(`Citología cervical · toma ${sample}`);
for (const title of [
'Detección de cáncer de cérvix',
'Condición ginecoobstétrica a la detección',
'Actualmente presenta',
'A la exploración se observa',
])
await expect(card.locator('dl.facts dt', { hasText: title })).toBeVisible();
// the earlier forms are collapsed, each with its own day
const earlier = card.locator('details.findings');
if (await earlier.count()) {
expect(await earlier.getAttribute('open')).toBeNull();
await earlier.locator('summary').click();
await expect(earlier.locator('tbody tr').first().locator('td').first()).toHaveText(
/\d{4}-\d{2}-\d{2}/,
);
}
// the tests keep date, study, report and the results of the study, without the form's antecedents
const table = tests(page);
await expect(table.getByRole('columnheader')).toHaveText([
'Toma',
'Estudio',
'Reporte',
'Resultados',
]);
const text = await table.innerText();
expect(text).toContain('Resultado (Bethesda)');
expect(text).not.toContain('Detección de cáncer de cérvix');
expect(text).not.toContain('A la exploración se observa');
// the extra findings are collapsed under their report
const findings = table.locator('details.findings').first();
await expect(findings.locator('summary')).toContainText('Hallazgos (');
expect(await findings.getAttribute('open')).toBeNull();
expect((await findings.locator('li').first().textContent())!.trim().length).toBeGreaterThan(0);
});
test('ficha (simulado): a missing antecedent says it is not documented; with none, no section', async ({
page,
}) => {
const { url } = await firstRecord(page);
const strip = (keep: string[]) =>
page.route('**/api/cacu/fhir/Observation**', async (route) => {
const response = await route.fetch();
const body = await response.json();
body.entry = (body.entry ?? []).filter((e: any) => {
const field = (e.resource.code?.coding?.[0]?.code ?? '').split('.').pop();
const antecedent = [
'screening_history',
'gynecologic_condition',
'presenting_symptom',
'cervix_appearance',
].includes(field);
return !antecedent || keep.includes(field);
});
await route.fulfill({
response,
body: JSON.stringify(body),
contentType: 'application/fhir+json',
});
});
await strip(['screening_history']);
await open(page, url);
const card = antecedents(page);
await expect(card.locator('dl.facts dd').first()).not.toHaveText('No documentado');
await expect(card.locator('dl.facts dd', { hasText: 'No documentado' })).toHaveCount(3);
await page.unroute('**/api/cacu/fhir/Observation**');
await strip([]);
await open(page, url);
await expect(antecedents(page)).toHaveCount(0);
// the record's tests are still there without them
await expect(tests(page).getByRole('table')).toBeVisible();
});
test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ page }) => {
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
const saved = page.waitForEvent('download');
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
const download = await saved;
expect(download.suggestedFilename()).toBe('expediente-cacu.pdf');
const file = await download.path();
expect(file).toBeTruthy();
const { readFileSync } = await import('node:fs');
const bytes = readFileSync(file!);
expect(bytes.subarray(0, 4).toString()).toBe('%PDF');
expect(bytes.length).toBeGreaterThan(5_000);
});
+85 -16
View File
@@ -107,23 +107,29 @@
</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" />
<p class="muted route-note">
Etapas de la citología{{ s[0].day ? ' del ' + s[0].day : '' }} a la fecha de corte
{{ cutoff() }}. «Inferida por fechas» es una asociación por cercanía de fechas, no
un vínculo clínico confirmado; un intervalo «(inferido)» depende de una etapa
inferida; «Pendiente» es una biopsia solicitada sin reporte a la fecha de corte;
«Sin dato» indica que no hay dato.
</p>
</div>
}
<table class="plain">
<thead>
<tr>
@@ -172,7 +178,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,12 +202,63 @@
</mat-card-content>
</mat-card>
@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>
<th>Toma</th>
@for (a of antecedents; track a.field) {
<th>{{ a.title }}</th>
}
</tr>
</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">
<mat-card-header
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<mat-card-content>
<app-risk-scales [scales]="scales()" />
<app-risk-scales [groups]="groups()" />
@if (models().length) {
<table class="plain">
<thead>
+24
View File
@@ -98,3 +98,27 @@ 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;
}
}
+48 -7
View File
@@ -21,7 +21,8 @@ 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 { ANTECEDENTS, Fact, group, split } from './record-groups';
import { 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,6 +52,15 @@ 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. */
@Component({
@@ -127,7 +137,7 @@ 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()));
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
protected readonly stages = computed(() => {
@@ -140,6 +150,10 @@ export class Paciente {
protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.models()) : [],
);
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */
protected readonly groups = computed(() =>
this.domain() === 'cacu' ? riskGroups(this.models()) : [],
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** CaCu: her record as a PDF. */
@@ -162,6 +176,7 @@ export class Paciente {
this.stages() ?? [],
this.history(),
this.tests(),
this.forms(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
@@ -178,19 +193,45 @@ export class Paciente {
const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[];
// the study's own results; the form's antecedents are in their own section and the extra
// findings are collapsed (record-groups)
const found = group(facts(results));
return {
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,
};
});
});
/** 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(() => {
const latest = new Map<string, RiskAssessment>();
+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']);
});
});
+48
View File
@@ -0,0 +1,48 @@
/** 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 };
}
+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',
+62
View File
@@ -0,0 +1,62 @@
import { horizon, 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 v3', 'Recurrencia v2', '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',
]);
});
});
+129 -32
View File
@@ -22,54 +22,151 @@ 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;
index?: string;
scales: { label: string; risk?: Prediction }[];
}
const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'],
];
/** 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) => ({ title: 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 }}{{ g.index ? ' · fecha índice ' + g.index : '' }}</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) {
<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>
}
}
`,
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: 24px;
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-marker {
background: #17324d;
bottom: -2px;
height: 20px;
position: absolute;
top: -4px;
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[]>();
}
+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) {
<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('; '),
);
}