Compare commits

..

4 Commits

Author SHA1 Message Date
Angel Capetillo Zavala df2dc7b95c Fit external CaCu donut labels within the existing charts 2026-11-30 16:06:37 -06:00
Angel Capetillo Zavala 44f3dce911 Integrate CaCu indicators, risk views and exports
Adapted from Angel Capetillo Zavala commits c0e4920 and 31400c7 and Edgar Hinojosas CaCu measures. Includes the existing 6F presentation and external donut labels.

Co-authored-by: edgar <edgar.hinojosas@uanl.edu.mx>
2026-11-30 16:02:00 -06:00
Angel Capetillo Zavala bc621f34f9 Regenerate client for CaCu exports and follow-up contracts 2026-11-30 16:01:58 -06:00
Angel Capetillo Zavala c5da898265 Regenerate API client for the existing rebuild contract 2026-11-30 15:59:46 -06:00
70 changed files with 4140 additions and 6576 deletions
-338
View File
@@ -1,338 +0,0 @@
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,
}) => {
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).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);
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();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
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 says where they went', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).toContainText('«Positivo»');
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([]);
});
}
-974
View File
@@ -1,974 +0,0 @@
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);
});
// ---- the NCI reference comparison (experimental) and the institutional curves ---------------------
const REFERENCE = '**/api/cacu/fhir/Patient/*/$reference-risk*';
const section = (page: Page) => page.locator('[data-section=referencia-nci]');
const value = (p: any) =>
p.valueCode ?? p.valueString ?? p.valueDate ?? p.valueInteger ?? p.valueDecimal ?? p.valueBoolean;
/** The first patients' answers of the API, to find one with a given state (the data is synthetic). */
async function referenceWhere(page: Page, status: string) {
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
for (const { resource } of patients.entry) {
const answer = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$reference-risk`);
if (!answer.ok()) throw new Error(`the reference operation answered ${answer.status()}`);
const body = await answer.json();
if (value(body.parameter.find((p: any) => p.name === 'status')) === status)
return { id: resource.id as string, body };
}
throw new Error(`no patient with the state ${status}`);
}
const part = (name: string, extra: object) => ({ name, ...extra });
const answerOf = (...parameter: object[]) => ({ resourceType: 'Parameters', parameter });
/** A resolved answer for fixtures, with the given horizons and comparisons. */
function fixture(
horizons: { years: number; reference?: number; comparison?: object[] }[],
more: object[] = [],
) {
return answerOf(
part('status', { valueCode: 'resolved' }),
part('experimental', { valueBoolean: true }),
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('source', {
part: [
part('id', { valueString: 'fixture-table' }),
part('file', { valueString: 'fixture.xlsx' }),
],
}),
...more,
...horizons.map((h) =>
part('horizon', {
part: [
part('years', { valueInteger: h.years }),
part('published', { valueBoolean: h.reference !== undefined }),
...(h.reference !== undefined ? [part('reference', { valueDecimal: h.reference })] : []),
...(h.comparison ?? []),
],
}),
),
);
}
const comparison = (status: string, reasons: string[], extra: object[] = []) =>
part('comparison', {
part: [
part('model', { valueCode: 'fixture.model' }),
part('title', { valueString: 'Modelo de prueba' }),
part('outcome', { valueString: 'CIN3+' }),
...extra,
part('status', { valueCode: status }),
...reasons.map((r) => part('reason', { valueCode: r })),
],
});
const answerWith = (page: Page, body: object, status = 200) =>
page.route(REFERENCE, (route) =>
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }),
);
test('referencia NCI: a resolved cytology shows its reference with scenario, source and no institutional model', async ({
page,
}) => {
const { id, body } = await referenceWhere(page, 'resolved');
await open(page, `/indicadores/cacu/pacientes/${id}`);
const box = section(page);
await expect(box).toBeVisible();
await expect(box.locator('dd[data-status=resolved]')).toHaveText('Referencia disponible');
await expect(box).toContainText('Tamizaje');
await expect(box).toContainText('CIN3 o más grave (CIN3+)');
await expect(box).toContainText('Master_NCI_Risk_Table.xlsx');
const rows = box.locator('tbody tr');
await expect(rows).toHaveCount(2);
await expect(rows.first()).toContainText('Inmediato (al índice)');
await expect(rows.nth(1)).toContainText('5 años');
// the figures are the API's: percent with two decimals, and no institutional model is made up
const expected = body.parameter
.filter((p: any) => p.name === 'horizon')
.map((h: any) =>
(h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2),
);
for (const [i, pct] of expected.entries())
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`);
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
// the antecedents used are collapsed
const used = box.locator('details.used');
expect(await used.getAttribute('open')).toBeNull();
await used.locator('summary').click();
await expect(used).toContainText('Fila de origen');
await expect(used).toContainText('Citología evaluada');
// the other risk displays of the record are still there, and the reference is below the scales
await expect(scale(page, FIVE)).toBeVisible();
const [scales, reference] = await Promise.all([
scale(page, FIVE).boundingBox(),
box.boundingBox(),
]);
expect(reference!.y).toBeGreaterThan(scales!.y);
await expect(
page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
).toBeVisible();
});
test('referencia NCI: a cytology the tables cannot resolve says the state and why, with no figure', async ({
page,
}) => {
const { id } = await referenceWhere(page, 'unverifiable_correspondence');
await open(page, `/indicadores/cacu/pacientes/${id}`);
const box = section(page);
await expect(box.locator('dd[data-status=unverifiable_correspondence]')).toHaveText(
'Correspondencia no verificable',
);
await expect(box.locator('ul.why li').first()).not.toBeEmpty();
await expect(box.locator('table')).toHaveCount(0);
await expect(box).not.toContainText('%');
});
test('referencia NCI: with the feature off (404) the section is not there and the record is whole', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
{ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] },
404,
);
await open(page, url);
await expect(section(page)).toHaveCount(0);
await expect(scale(page, FIVE)).toBeVisible();
});
test('referencia NCI (simulado): a comparison that is valid shows the difference as institutional minus reference', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 5,
reference: 0.0027,
comparison: [
comparison(
'comparable',
[],
[
part('institutional', { valueDecimal: 0.0127 }),
part('institutional-low', { valueDecimal: 0.005 }),
part('institutional-high', { valueDecimal: 0.02 }),
part('difference-pp', { valueDecimal: 1 }),
],
),
],
},
]),
);
await open(page, url);
const row = section(page).locator('tbody tr').first();
await expect(row).toContainText('Modelo de prueba');
await expect(row).toContainText('1.27 %');
await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
await expect(row.locator('td').nth(3)).toContainText('+1.00');
await expect(row.locator('td').nth(3)).not.toContainText('No comparable');
});
test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(
page,
fixture([
{
years: 0,
reference: 0.0001,
comparison: [
comparison(
'not_comparable',
['outcome_differs', 'horizon_not_published_by_model', 'population_not_verified'],
[part('institutional', { valueDecimal: 0.05 })],
),
],
},
{ years: 5, reference: 0.0027 },
]),
);
await open(page, url);
const first = section(page).locator('tbody tr').first();
await expect(first.locator('td').nth(3)).toContainText('No comparable');
await expect(first.locator('td').nth(3)).toContainText(
'El desenlace del modelo no es el de la tabla (CIN3+)',
);
await expect(first.locator('td').nth(3)).toContainText(
'no publica una predicción a este horizonte',
);
await expect(first.locator('td').nth(3)).not.toContainText(/[+-]\d/); // no signed difference
await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted
});
test('referencia NCI (simulado): a year-one reference is a year, never the immediate risk; a blank is not zero', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
await open(page, url);
const rows = section(page).locator('tbody tr');
await expect(rows.first()).toContainText('1 año');
await expect(section(page)).not.toContainText('Inmediato');
await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado');
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %');
});
for (const width of [1440, 480]) {
test(`referencia NCI (simulado) at ${width} px: the section lays out cleanly beside the scales and curves`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { url } = await firstRecord(page);
await answerWith(
page,
fixture(
[
{
years: 0,
reference: 0.0001,
comparison: [
comparison(
'not_comparable',
['outcome_differs', 'population_not_verified'],
[part('institutional', { valueDecimal: 0.05 })],
),
],
},
{
years: 5,
reference: 0.0027,
comparison: [
comparison(
'comparable',
[],
[
part('institutional', { valueDecimal: 0.0127 }),
part('difference-pp', { valueDecimal: 1 }),
],
),
],
},
],
[part('assumption', { valueString: 'un supuesto sin verificar' })],
),
);
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
]),
]);
await open(page, url);
await section(page).locator('details.used summary').click();
await page.waitForTimeout(800);
expect(await layoutProblems(page)).toEqual([]);
expect(
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
).toBe(true);
});
}
test('curvas (simulado): one series per model at its published horizons, its band only where it has intervals, and no NCI data', async ({
page,
}) => {
const { url } = await firstRecord(page);
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
await withRisks(page, [
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
[1, 0.08, 0.05, 0.12],
[3, 0.21, 0.15, 0.28],
[5, 0.34, 0.26, 0.44],
]),
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
[1, 0.002, 0.001, 0.005],
[3, 0.008],
[5, 0.015, 0.008, 0.028],
]),
risk('c', 'Sin intervalo v1', 'cacu.other', '2026-06-01', [
[2, 0.1],
[4, 0.2],
]),
risk('d', 'Un punto v1', 'cacu.partial', '2026-06-01', [[5, 0.5]]),
]);
await open(page, url);
const card = page.locator('details.curves');
await expect(card.locator('summary')).toHaveText('Curvas de probabilidad con su intervalo');
await expect(card).toHaveAttribute('open', '');
await expect(card.locator('li').first()).toContainText(
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 % (IC 95 %: 5.0–12.0 %); 3 años: 21.0 %',
);
const plot = await card.locator('.js-plotly-plot').evaluate((e: any) => ({
names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name),
series: Object.fromEntries(
e.data.filter((t: any) => t.mode?.includes('markers')).map((t: any) => [t.name, t.x]),
),
bands: e.data.filter((t: any) => t.fill === 'tonexty').map((t: any) => t.name),
ticks: e.layout.xaxis.tickvals,
title: e.layout.xaxis.title.text,
}));
expect(plot.series).toEqual({
'Riesgo LIEAG+': [1, 3, 5],
'Riesgo cáncer': [1, 3, 5],
'Sin intervalo': [2, 4],
'Un punto': [5],
});
expect(plot.bands).toEqual(['IC 95 % Riesgo LIEAG+', 'IC 95 % Riesgo cáncer']); // none for the models without intervals
expect(plot.ticks).toEqual([1, 2, 3, 4, 5]);
expect(plot.title).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
// the reference is a separate table: its 0.27 % is nowhere in the figure
expect(
JSON.stringify(await card.locator('.js-plotly-plot').evaluate((e: any) => e.data)),
).not.toContain('0.27');
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
});
+335 -33
View File
@@ -59,10 +59,10 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
@@ -73,7 +73,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText('Página 2 de')).toBeVisible();
await expect(page.getByText(/Página 2 de \d+, \d+ registros/)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
@@ -103,12 +103,13 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible();
// a node's caption: its kind, then its name
await page.locator('.node-caption', { hasText: 'Fuente de datosPacientes' }).click();
await page.locator('.node-caption', { hasText: 'Pacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page;
await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
@@ -197,53 +198,80 @@ function captured(domain: string) {
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
return items
const old = items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
return domain === 'cacu' ? rearranged(old) : old;
}
/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the
* opportunity section, under its cards, and the cytology distribution is a table in the joint
* results card (its nested donut is not drawn any more). Nothing else of the old page moves. */
function rearranged(old: any[]) {
const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje');
const moved = old.splice(route, 2); // its heading and its plot
old.splice(
old.findIndex((i) => i.text === 'Indicadores clínicos'),
0,
moved[0],
moved[1],
);
// the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the
// cytology section, under another title) are not headings of this page any more
return old.filter(
(i) =>
!/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test(
i.text ?? '',
),
);
}
/** Sections this platform adds to an old page, by domain, in the order they appear. The old
* headings still have to appear, in their order; nothing else may appear (a figure's own
* `h3.figure-title` inside a measure's card is the card's, not a section). */
const ADDED: Record<string, string[]> = {
cacu: [
'Resultados de citología, VPH y biopsia',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
'VPP tras colposcopía registrada',
],
};
/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */
function oldThenAdded(actual: string[], old: string[], added: string[]) {
const extra: string[] = [];
let found = 0;
for (const heading of actual) {
if (found < old.length && heading === old[found]) found++;
else extra.push(heading);
}
return { allOldInOrder: found === old.length, extra, added };
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
for (const domain of ['cama', 'tea']) {
for (const domain of ['cacu', 'cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const all = captured(domain);
// CaMa's five timeliness boxes are one route card now: its heading stands for them.
const route = all.findIndex(
(i) => i.kind === 'h3' && i.text === 'Tiempo de tamizaje a diagnóstico',
);
const clinical = all.findIndex((i) => i.text === 'Indicadores clínicos');
// Lote 2: the detection rate has its own title, and the histopathology figures are two
// cards (the result by BI-RADS; the confirmation in two readings).
const detection = (i: { text?: string }) =>
i.text === 'Tasa de confirmación histopatológica'
? { ...i, text: 'Tasa de detección histopatológica' }
: i;
const results = all.findIndex(
(i) => i.text === 'Resultado histopatológico por categoría BI-RADS',
);
const cards = [
{ kind: 'h3', text: 'Resultado histopatológico por categoría BI-RADS' },
{ kind: 'h3', text: 'Confirmación histopatológica' }, // one card: title, tabs and reading
];
const old =
domain === 'cama'
? [...all.slice(0, route + 1).map(detection), ...all.slice(clinical, results), ...cards]
: all;
const old = captured(domain);
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// textContent: a heading inside a collapsed section (CaCu's original confirmation measure)
// is still a heading of the page, though the browser gives it no rendered text.
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
.locator('h2, h3:not(.figure-title)')
.evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()));
const from = headings.indexOf('Indicadores de oportunidad');
expect(headings.slice(from).map(period)).toEqual(
const seen = oldThenAdded(
headings.slice(from).map(period),
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
ADDED[domain] ?? [],
);
expect(seen.allOldInOrder).toBe(true);
expect(seen.extra).toEqual(seen.added);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
@@ -313,6 +341,280 @@ for (const domain of ['cacu', 'cama', 'tea']) {
});
}
test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({
page,
}) => {
const asked: string[] = [];
page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url()));
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// cumulative (the default), step by step with its warning and quartiles, and by ICD-10
// the route's times are in the opportunity section, after its cards and before the clinical ones
const opportunity = tab.locator('section.opportunity');
await expect(opportunity.locator('.route-card')).toBeVisible();
await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0);
expect(
await opportunity.evaluate((el) => {
const kpis = el.querySelector('.kpis')!;
const card = el.querySelector('.route-card')!;
return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING);
}),
).toBe(true);
await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible();
await tab.getByRole('radio', { name: 'Por pasos' }).click();
// by steps: independent bars from zero in a table, every step kept, and the medians not added
const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' });
await expect(steps).toBeVisible();
await expect(steps.locator('tbody tr')).toHaveCount(4);
await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible();
await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0);
await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click();
await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible();
await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click();
await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible();
await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible();
// the sections of the new measures: each one in the place of its subject
for (const measure of [
'CACU_VPH_GENOTIPO',
'CACU_VPH',
'CACU_BIOPSIA_RESULTADOS',
'CACU_VPP_COLPOSCOPIA',
])
await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible();
// a PPV says what it is and what it is not
await expect(
tab
.locator('[data-measure="CACU_VPP_COLPOSCOPIA"]')
.getByText('no un vínculo clínico confirmado'),
).toBeVisible();
// the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut
const joint = tab.locator('.results-card');
const [cyto, hpv, biopsy] = await Promise.all(
['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) =>
joint.locator(`section[data-measure="${m}"]`).boundingBox(),
),
);
expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2);
expect(cyto!.x).toBeLessThan(hpv!.x);
expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1);
expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8);
await expect(
joint.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(joint.getByText('Menor que LIEAG')).toBeVisible();
await expect(joint.getByText('LIEAG o más')).toBeVisible();
// three HPV categories are not listed, and the page says so only when it has such reports
const hpvRows = await joint
.locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th')
.allInnerTexts();
for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable'])
expect(hpvRows.join('|')).not.toContain(hidden);
// the cytology column reads one way at a time: the general table, or the clinical scenarios
const cytology = joint.locator('section[data-measure="CACU_EU7"]');
await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked();
await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0);
await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click();
await expect(cytology.locator('.js-plotly-plot')).toBeVisible();
await expect(cytology.getByRole('table')).toHaveCount(0);
await expect(
cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'),
).toBeVisible();
await expect(cytology.locator('.legend li')).toHaveCount(6);
await cytology.getByRole('radio', { name: 'Distribución general' }).click();
await expect(
cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(
joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'),
).toHaveCount(0);
await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0);
// the confirmation card: one perspective at a time, each with its own PPV and its readings
const confirmation = tab.locator('.confirmation-card');
await expect(
confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }),
).toBeVisible();
await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible();
await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked();
for (const [perspective, measure, title] of [
['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'],
['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'],
]) {
await confirmation.getByRole('radio', { name: perspective, exact: true }).click();
await expect(confirmation.locator('app-ppv-card')).toHaveCount(1);
const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`);
await expect(ppv.getByRole('heading', { name: title })).toBeVisible();
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
await expect(ppv.locator('.ppv-rows')).toHaveCount(0);
for (const mode of [
'Citología previa',
'VPH previo',
'Nivel de histología',
'Ronda de tamizaje',
]) {
await ppv.getByRole('radio', { name: mode, exact: true }).click();
await expect(ppv.getByRole('table', { name: mode })).toBeVisible();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0);
await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
// the score line and the methodological note stay in view in every reading
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
}
await ppv.getByRole('radio', { name: 'Total' }).click();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
}
// the biopsy requests are one more reading of the biopsy perspective, with their own heading
const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]');
await expect(
biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }),
).toBeVisible();
await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }),
).toBeVisible();
await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount(
0,
);
await expect(biopsyPpv.locator('.measure-score')).toContainText(
'solicitudes registradas (no pacientes)',
);
await expect(
biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'),
).toBeVisible();
await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible();
await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible();
await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos');
await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0);
await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }),
).toBeVisible();
// the original confirmation measure is not shown on this tab any more
await expect(confirmation.locator('details')).toHaveCount(0);
await expect(tab.getByText('medida original')).toHaveCount(0);
await expect(tab.getByText('Denominador: ')).toHaveCount(0);
// the tabs are short and the full explanation is in the tab's content
await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = confirmation.locator('app-ppv-card');
await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click();
await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas');
await expect(colposcopy.getByRole('radio')).toHaveCount(5);
const tops = await colposcopy
.locator('mat-button-toggle')
.evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size);
expect(tops).toBe(1); // one line on desktop
// the patients by HPV result: the whole as a donut, then one breakdown at a time
const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible();
await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
for (const mode of [
'Por grupo de edad',
'Por estatus de seguimiento',
'Por genotipo',
'Por tamizaje inicial o subsecuente',
]) {
await vph.getByRole('radio', { name: mode, exact: true }).click();
await expect(vph.getByRole('table', { name: mode })).toBeVisible();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(0);
await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
}
await vph.getByRole('radio', { name: 'Total' }).click();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
// the two HPV measures are told apart: reports against patients
await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText(
'Pacientes evaluadas por resultado de VPH',
);
await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText(
'Cuenta reportes, no pacientes',
);
expect(asked).toEqual([]);
});
test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const rows = page.locator('table.worklist tbody tr:not(.stage-panel)');
await expect(rows.first().locator('a')).toBeVisible();
const total = async () =>
Number(
/(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0,
);
// her age at the cut-off, and the stages: a compact line with a chevron that opens the panel
await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible();
await expect(rows.first().locator('app-stages .node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click();
const panel = page.locator('tr.stage-panel');
await expect(panel).toContainText('Toma de muestra');
await expect(panel).toContainText('Desde anterior');
await expect(panel.locator('.node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click();
await expect(panel).toHaveCount(0);
// the age filters apply before the page is cut; the name search of Rebuild is still there
const all = await total();
await page.getByLabel('Edad mínima').fill('200');
await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible();
await page.getByLabel('Edad mínima').fill('45');
await expect(async () => expect(await total()).toBeLessThan(all)).toPass();
await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible();
await page.getByRole('button', { name: 'Limpiar edades' }).click();
await expect(async () => expect(await total()).toBe(all)).toPass();
// the whole query, as the two files
const [pdf] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar PDF' }).click(),
]);
expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf');
expect(
readFileSync((await pdf.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
const [xlsx] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(),
]);
expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx');
expect(
readFileSync((await xlsx.path())!)
.subarray(0, 2)
.toString(),
).toBe('PK');
// her record: age, the detailed stages, the scales, and the file
await rows.first().locator('a').first().click();
await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:');
await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5);
await expect(page.getByText('Desde toma:').first()).toBeVisible();
await expect(page.getByText('Riesgo inmediato')).toBeVisible();
await expect(page.getByText('Riesgo a 5 años')).toBeVisible();
const [ficha] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar ficha PDF' }).click(),
]);
expect(
readFileSync((await ficha.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
expect(problems).toEqual([]);
});
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
-88
View File
@@ -1,88 +0,0 @@
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',
});
});
}
+203 -10
View File
@@ -328,6 +328,88 @@
"title": "Correction",
"type": "object"
},
"Document": {
"properties": {
"columns": {
"items": {
"type": "string"
},
"maxItems": 12,
"minItems": 1,
"title": "Columns",
"type": "array"
},
"parameters": {
"items": {
"items": {
"type": "string"
},
"type": "array"
},
"maxItems": 30,
"title": "Parameters",
"type": "array"
},
"risk_scales": {
"items": {
"additionalProperties": true,
"type": "object"
},
"maxItems": 40,
"title": "Risk Scales",
"type": "array"
},
"row_stages": {
"items": {
"items": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"type": "array"
},
"maxItems": 5000,
"title": "Row Stages",
"type": "array"
},
"rows": {
"items": {
"items": {
"type": "string"
},
"type": "array"
},
"maxItems": 5000,
"title": "Rows",
"type": "array"
},
"timeline": {
"items": {
"additionalProperties": {
"type": "string"
},
"type": "object"
},
"maxItems": 5,
"title": "Timeline",
"type": "array"
},
"title": {
"maxLength": 150,
"title": "Title",
"type": "string"
}
},
"required": [
"title",
"parameters",
"columns",
"rows"
],
"title": "Document",
"type": "object"
},
"Domain": {
"enum": [
"cacu",
@@ -2790,6 +2872,75 @@
]
}
},
"/cacu/exports/capabilities": {
"get": {
"operationId": "capabilities",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {}
}
},
"description": "Successful Response"
}
},
"summary": "Capabilities",
"tags": [
"exports"
]
}
},
"/cacu/exports/{kind}": {
"post": {
"operationId": "export",
"parameters": [
{
"in": "path",
"name": "kind",
"required": true,
"schema": {
"title": "Kind",
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Document"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {}
}
},
"description": "Successful Response"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
"description": "Validation Error"
}
},
"summary": "Export",
"tags": [
"exports"
]
}
},
"/domains": {
"get": {
"operationId": "domains",
@@ -5107,7 +5258,7 @@
},
"/{domain}/fhir/DiagnosticReport": {
"get": {
"description": "The domain's reports (each study of the catalog with a report), as known by the last\nday with data.",
"description": "The domain's reports (each study of the catalog with a report), as known by the last\nday with data (CaCu: or by `stage-cutoff`, for the stages of each sample's route).",
"operationId": "search_diagnostic_report",
"parameters": [
{
@@ -5136,6 +5287,23 @@
"title": "Subject"
}
},
{
"in": "query",
"name": "stage-cutoff",
"required": false,
"schema": {
"anyOf": [
{
"format": "date",
"type": "string"
},
{
"type": "null"
}
],
"title": "Stage-Cutoff"
}
},
{
"in": "query",
"name": "_count",
@@ -5728,18 +5896,43 @@
}
},
{
"description": "gt, ge, lt or le and a day (2000-12-31)",
"description": "CaCu: completed years at the cut-off",
"in": "query",
"name": "birthdate",
"name": "follow-up-age-min",
"required": false,
"schema": {
"default": [],
"description": "gt, ge, lt or le and a day (2000-12-31)",
"items": {
"type": "string"
},
"title": "Birthdate",
"type": "array"
"anyOf": [
{
"maximum": 150,
"minimum": 0,
"type": "integer"
},
{
"type": "null"
}
],
"description": "CaCu: completed years at the cut-off",
"title": "Follow-Up-Age-Min"
}
},
{
"description": "CaCu: completed years at the cut-off",
"in": "query",
"name": "follow-up-age-max",
"required": false,
"schema": {
"anyOf": [
{
"maximum": 150,
"minimum": 0,
"type": "integer"
},
{
"type": "null"
}
],
"description": "CaCu: completed years at the cut-off",
"title": "Follow-Up-Age-Max"
}
},
{
+2 -285
View File
@@ -25,11 +25,9 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.3.0",
@@ -40,7 +38,6 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
@@ -2405,30 +2402,6 @@
"@ngx-formly/core": "11.2.0"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@oxc-parser/binding-android-arm-eabi": {
"version": "0.158.0",
"resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.158.0.tgz",
@@ -3492,12 +3465,6 @@
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"license": "MIT"
},
"node_modules/@swc/helpers": {
"version": "0.5.24",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
"integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
@@ -3603,37 +3570,6 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/node": {
"version": "26.6.11",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/pdfkit": {
"version": "0.17.7",
"resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz",
"integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/pdfmake": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/@types/pdfmake/-/pdfmake-0.3.5.tgz",
"integrity": "sha512-AQI4ISWzt7qmnKaipkikibz9x2XIvU/1zqfEHwKhBU7vP6oIhlGoLB9KsSIAryH7f9uuJebXScldb6F4ebwFxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/pdfkit": "*"
}
},
"node_modules/@types/plotly.js": {
"version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-3.0.15.tgz",
@@ -3880,15 +3816,6 @@
"node": ">=12"
}
},
"node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.39",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.39.tgz",
@@ -3964,35 +3891,6 @@
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/brotli/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/browserslist": {
"version": "4.29.6",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz",
@@ -4221,15 +4119,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/colorjs.io": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.7.1.tgz",
@@ -4437,12 +4326,6 @@
"node": ">=8"
}
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/dom-serializer": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
@@ -4678,6 +4561,7 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-string-truncated-width": {
@@ -4742,12 +4626,6 @@
}
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/flru": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz",
@@ -4758,23 +4636,6 @@
"node": ">=6"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/fs-extra": {
"version": "11.4.1",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
@@ -5505,16 +5366,6 @@
"url": "https://opencollective.com/parcel"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/listr2": {
"version": "11.4.1",
"resolved": "https://registry.npmjs.org/listr2/-/listr2-11.4.1.tgz",
@@ -5993,12 +5844,6 @@
"@oxc-parser/binding-win32-x64-msvc": "0.158.0"
}
},
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/parse5": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
@@ -6077,34 +5922,6 @@
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/pdfmake": {
"version": "0.3.14",
"resolved": "https://registry.npmjs.org/pdfmake/-/pdfmake-0.3.14.tgz",
"integrity": "sha512-EDyOlwiDnE8e0eITSpHwZCVAP/veWq0TxA2RyhoDO0cSLat7HEGNtKUN6UiW9+YovO2GhcWlK99Q7tj9sof9gg==",
"license": "MIT",
"dependencies": {
"linebreak": "^1.1.0",
"pdfkit": "^0.20.2",
"xmldoc": "^2.0.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6173,14 +5990,6 @@
"integrity": "sha512-3UkyAT7/U8f3sOLavLnUjA6mqFmnqEe246GZhxT0J3TT9oZ0mh6SgwsL1yo/3/4xfmRSDFdGOxe+EsvT2XiE0g==",
"license": "MIT"
},
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": {
"version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
@@ -6356,12 +6165,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/rolldown": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.1.tgz",
@@ -6860,15 +6663,6 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/sax": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/saxes": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
@@ -7058,12 +6852,6 @@
"node": ">=16.0.0"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinybench": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
@@ -7191,53 +6979,6 @@
"node": ">=22.19.0"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-properties/node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
@@ -7935,18 +7676,6 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/write-excel-file": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/write-excel-file/-/write-excel-file-4.1.1.tgz",
"integrity": "sha512-MUnCnNtQrcZek832ZcU24uU0rSphFmKPD1DvIjXOlygVb93CV7Tme6H3jUTkxsMmjB2W7HIzERzjqTi5kui71A==",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -7964,18 +7693,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/xmldoc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
"integrity": "sha512-6gRk4NY/Jvg67xn7OzJuxLRsGgiXBaPUQplVJ/9l99uIugxh4FTOewYz5ic8WScj7Xx/2WvhENiQKwkK9RpE4w==",
"license": "MIT",
"dependencies": {
"sax": "^1.4.3"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/xxhash-wasm": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+1 -4
View File
@@ -29,11 +29,9 @@
"d3-zoom": "3.0.0",
"material-symbols": "0.48.3",
"ngx-vflow": "2.7.0",
"pdfmake": "0.3.14",
"plotly.js-cartesian-dist-min": "4.1.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"write-excel-file": "4.1.1"
"tslib": "^2.3.0"
},
"devDependencies": {
"@angular/build": "^22.3.0",
@@ -44,7 +42,6 @@
"@types/d3-selection": "3.0.13",
"@types/d3-zoom": "3.0.9",
"@types/fhir": "0.0.44",
"@types/pdfmake": "0.3.5",
"@types/plotly.js": "3.0.15",
"jsdom": "^31.0.0",
"ng-openapi-gen": "^1.1.0",
+29
View File
@@ -0,0 +1,29 @@
/* 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';
export interface Capabilities$Params {
}
export function capabilities(http: HttpClient, rootUrl: string, params?: Capabilities$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, capabilities.PATH, 'get');
if (params) {
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
capabilities.PATH = '/cacu/exports/capabilities';
+34
View File
@@ -0,0 +1,34 @@
/* 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 { Document } from '../../models/document';
export interface Export$Params {
kind: string;
body: Document
}
export function export$(http: HttpClient, rootUrl: string, params: Export$Params, context?: HttpContext): Observable<StrictHttpResponse<any>> {
const rb = new RequestBuilder(rootUrl, export$.PATH, 'post');
if (params) {
rb.path('kind', params.kind, {});
rb.body(params.body, 'application/json');
}
return http.request(
rb.build({ responseType: 'json', accept: 'application/json', context })
).pipe(
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
map((r: HttpResponse<any>) => {
return r as StrictHttpResponse<any>;
})
);
}
export$.PATH = '/cacu/exports/{kind}';
@@ -16,6 +16,7 @@ export interface SearchDiagnosticReport$Params {
* Patient/<id>, comma-separated
*/
subject?: (string | null);
'stage-cutoff'?: (string | null);
'_count'?: (number | null);
'_offset'?: number;
}
@@ -26,6 +27,7 @@ export function searchDiagnosticReport(http: HttpClient, rootUrl: string, params
if (params) {
rb.path('domain', params.domain, {});
rb.query('subject', params.subject, {});
rb.query('stage-cutoff', params['stage-cutoff'], {});
rb.query('_count', params['_count'], {});
rb.query('_offset', params['_offset'], {});
}
+9 -3
View File
@@ -35,9 +35,14 @@ export interface SearchPatient$Params {
identifier?: (string | null);
/**
* gt, ge, lt or le and a day (2000-12-31)
* CaCu: completed years at the cut-off
*/
birthdate?: Array<string>;
'follow-up-age-min'?: (number | null);
/**
* CaCu: completed years at the cut-off
*/
'follow-up-age-max'?: (number | null);
/**
* -recent or -risk-<outcome>
@@ -73,7 +78,8 @@ export function searchPatient(http: HttpClient, rootUrl: string, params: SearchP
rb.query('follow-up-status', params['follow-up-status'], {});
rb.query('name', params.name, {});
rb.query('identifier', params.identifier, {});
rb.query('birthdate', params.birthdate, {});
rb.query('follow-up-age-min', params['follow-up-age-min'], {});
rb.query('follow-up-age-max', params['follow-up-age-max'], {});
rb.query('_sort', params['_sort'], {});
rb.query('risk-horizon', params['risk-horizon'], {});
rb.query('_revinclude', params['_revinclude'], {});
+4
View File
@@ -5,6 +5,10 @@ export type { AuthCookieLogin$Params as AuthCookieLogin$Params } from './fn/auth
export { authCookieLogin as authCookieLogin } from './fn/auth/auth-cookie-login';
export type { AuthCookieLogout$Params as AuthCookieLogout$Params } from './fn/auth/auth-cookie-logout';
export { authCookieLogout as authCookieLogout } from './fn/auth/auth-cookie-logout';
export type { Capabilities$Params as Capabilities$Params } from './fn/exports/capabilities';
export { capabilities as capabilities } from './fn/exports/capabilities';
export type { Export$Params as Export$Params } from './fn/exports/export';
export { export$ as export$ } from './fn/exports/export';
export type { Domains$Params as Domains$Params } from './fn/operations/domains';
export { domains as domains } from './fn/operations/domains';
export type { Health$Params as Health$Params } from './fn/operations/health';
+1
View File
@@ -9,6 +9,7 @@ export type { Browsed } from './models/browsed';
export type { Catalog } from './models/catalog';
export type { Condition } from './models/condition';
export type { Correction } from './models/correction';
export type { Document } from './models/document';
export type { Domain } from './models/domain';
export type { Entry } from './models/entry';
export type { ErrorModel } from './models/error-model';
+18
View File
@@ -0,0 +1,18 @@
/* eslint-disable */
/* Code generated by ng-openapi-gen DO NOT EDIT. */
export interface Document {
columns: Array<string>;
parameters: Array<Array<string>>;
risk_scales?: Array<{
[key: string]: any;
}>;
row_stages?: Array<Array<{
[key: string]: string;
}>>;
rows: Array<Array<string>>;
timeline?: Array<{
[key: string]: string;
}>;
title: string;
}
+2 -4
View File
@@ -33,8 +33,6 @@ export interface SourceDialogData {
guided?: Guided | null;
label?: string;
}
const NONE: string[] = [];
/** What it gives back: the dialog's answers (the node's dlt fields are made from them). */
export interface SourceDialogResult {
guided: Guided;
@@ -205,17 +203,17 @@ export class SourceDialog {
}
}
/** The tables a database listed, for its table field. */
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : NONE; // a new list each time renders forever
return Array.isArray(v) ? (v as string[]) : [];
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
/** The tables a database listed, for its table field. */
protected tables(): string[] {
return this.tableList();
}
+57
View File
@@ -0,0 +1,57 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
export interface ExportStage {
state: string;
provenance?: string;
label?: string;
date?: string;
prev?: string;
start?: string;
}
export interface ExportRiskScale {
label: string;
value?: number;
low?: number;
high?: number;
outcome?: string;
model?: string;
horizon?: string;
}
export interface ExportDocument {
title: string;
parameters: string[][];
columns: string[];
rows: string[][];
timeline?: ExportStage[];
row_stages?: ExportStage[][];
risk_scales?: ExportRiskScale[];
}
export async function downloadDocument(
http: HttpClient,
format: 'pdf' | 'xlsx',
doc: ExportDocument,
) {
let blob: Blob;
try {
blob = await firstValueFrom(
http.post(`/api/cacu/exports/${format}`, doc, { responseType: 'blob' }),
);
} catch (error) {
if (error instanceof HttpErrorResponse && error.error instanceof Blob) {
try {
const body = JSON.parse(await error.error.text());
if (typeof body.detail === 'string') throw new Error(body.detail);
} catch (parsed) {
if (parsed instanceof Error && !(parsed instanceof SyntaxError)) throw parsed;
}
}
throw error;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cacu-${format === 'pdf' ? 'reporte.pdf' : 'seguimiento.xlsx'}`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
}
-69
View File
@@ -1,69 +0,0 @@
import type { Content, TDocumentDefinitions } from 'pdfmake/interfaces';
/** A table to save, as the page shows it: its headers and rows, and what it was asked with. */
export interface Sheet {
title: string;
query?: [string, string][];
head: string[];
rows: string[][];
}
/** Every cell is text: nothing in it runs as a formula. */
export async function saveExcel(sheet: Sheet, file: string): Promise<void> {
const { default: write } = await import('write-excel-file/browser');
const text = (value: string) => ({ value, type: String });
const head = sheet.head.map((value) => ({ ...text(value), fontWeight: 'bold' as const }));
await write([
{ sheet: 'Resultados', data: [head, ...sheet.rows.map((r) => r.map(text))] },
{ sheet: 'Consulta', data: (sheet.query ?? []).map((q) => q.map(text)) },
]).toFile(`${file}.xlsx`);
}
/** The tables on the institutional page: logo, date and page numbers. */
export async function savePdf(sheets: Sheet[], file: string, wide = false): Promise<void> {
const [pdfmake, fonts, logo] = await Promise.all([
import('pdfmake/build/pdfmake'),
import('pdfmake/build/vfs_fonts'),
fetch('assets/branding/isssteleon-logo.png').then((r) => r.blob()),
]);
const image = await new Promise<string>((done, fail) => {
const reader = new FileReader();
reader.onload = () => done(reader.result as string);
reader.onerror = () => fail(reader.error);
reader.readAsDataURL(logo);
});
const made = new Date().toLocaleString('es-MX', { dateStyle: 'medium', timeStyle: 'short' });
const definition: TDocumentDefinitions = {
pageSize: 'LETTER',
pageOrientation: wide ? 'landscape' : 'portrait',
pageMargins: [36, 60, 36, 40],
defaultStyle: { fontSize: 7.5 },
header: { image, width: 110, margin: [36, 18, 0, 0] },
footer: (page, pages) => ({
columns: [
`Generado: ${made}`,
{ text: 'Confidencial, uso interno', alignment: 'center' },
{ text: `Página ${page} de ${pages}`, alignment: 'right' },
],
margin: [36, 12],
fontSize: 7,
}),
content: sheets.flatMap((s): Content[] => [
{ text: s.title, fontSize: 13, bold: true, margin: [0, 10, 0, 4] },
...(s.query ?? []).map(([k, v]) => ({ text: [{ text: `${k}: `, bold: true }, v] })),
s.rows.length
? {
layout: 'lightHorizontalLines',
margin: [0, 6, 0, 0],
table: {
headerRows: 1,
dontBreakRows: true,
body: [s.head.map((text) => ({ text, bold: true })), ...s.rows],
},
}
: 'Sin registros.',
]),
};
pdfmake.default.addVirtualFileSystem(fonts.default);
await pdfmake.default.createPdf(definition).download(`${file}.pdf`);
}
-417
View File
@@ -1,417 +0,0 @@
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { scenarioBars } from './figures';
import { Reading } from './measures';
describe('bars', () => {
it('list every category, so the shares add up', () => {
const r: Reading = {
populations: {},
strata: {
category: { a: { 'initial-population': 3 }, other: { 'initial-population': 1 } },
},
};
const catalog = [{ code: 'a', label: 'A', color: '#000' }];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog }, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '75.0 %'],
['1', '25.0 %'],
]);
});
it('a group with no patients has no rate', () => {
const r: Reading = {
populations: {},
strata: { s: { initial: { numerator: 0, denominator: 0 } } },
};
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)!;
expect(t.rows.map((x) => [x.label, ...x.cells])).toEqual([
['Con', '1', '25.0 %'],
['Sin', '3', '75.0 %'],
]);
});
it('rows with patients and no biopsy are not rows with no patients; malignant counts only graded', () => {
const r: Reading = {
populations: {},
strata: {
birads: {
'4A': { 'initial-population': 3 },
'5': { 'initial-population': 4 },
'6': { 'initial-population': 2 },
},
'birads-category': {
'4A|no_biopsy': { 'initial-population': 3 },
'5|benign': { 'initial-population': 1 },
'5|invasive': { 'initial-population': 1 },
'5|no_data': { 'initial-population': 2 },
'6|no_data': { 'initial-population': 2 },
},
},
};
const results = [
{ code: 'benign', label: 'Benigno', color: '#1' },
{ code: 'invasive', label: 'Invasor', color: '#2' },
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#3' },
{ code: 'no_data', label: 'Sin dato', color: '#4' },
];
const rows = ['4A', '5', '6', '4B'].map((code) => ({ code, label: code, color: '#0' }));
const mode = {
kind: 'outcomes',
label: 'x',
measure: 'M',
stratum: 'birads',
rows,
results,
malignant: ['invasive'],
};
const t = bars(mode as any, () => r)!;
expect(t.rows.map((x) => x.cells)).toEqual([
['3', '0', '0', '3', '0', 'Sin biopsias'],
['4', '1', '1', '0', '2', '1/2 (50.0 %)'],
['2', '0', '0', '0', '2', 'Sin biopsias clasificables'],
['0', '—', '—', '—', '—', '—'],
]);
expect(t.rows.map((x) => x.none)).toEqual([
undefined,
undefined,
undefined,
'Sin pacientes en el periodo',
]);
expect(t.rows[1].segments!.map((x) => x.width)).toEqual([25, 25, 0, 50]);
});
it('bars on a percent scale are as long as the shares shown', () => {
const r: Reading = {
populations: {},
strata: { category: { a: { 'initial-population': 1 }, b: { 'initial-population': 3 } } },
};
const catalog = [
{ code: 'a', label: 'A', color: '#0' },
{ code: 'b', label: 'B', color: '#1' },
{ code: 'c', label: 'C', color: '#2' },
];
const t = bars({ kind: 'counts', label: 'x', measure: 'M', catalog, percent: true }, () => r)!;
expect(t.rows.map((x) => x.width)).toEqual([25, 75, 0]);
expect(t.rows.map((x) => x.cells)).toEqual([
['1', '25.0 %'],
['3', '75.0 %'],
['0', '0.0 %'],
]);
});
it('a split takes the colours it is given', () => {
const r: Reading = { populations: { numerator: 1, denominator: 4 }, strata: {} };
const mode = {
kind: 'split',
label: 'x',
measure: 'M',
yes: 'Con',
no: 'Sin',
colors: ['#a', '#b'],
};
expect(bars(mode as any, () => r)!.rows.map((x) => x.color)).toEqual(['#a', '#b']);
});
});
-539
View File
@@ -1,539 +0,0 @@
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. */
export type Category = { code: string; label: string; color: string };
/** One way of reading a card, as bars from the reports, or a figure. */
export type Mode = {
label: string;
caption?: string;
/** said above the table: what its rows count (patients, reported biopsies…) */
heading?: string;
} & (
| {
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[];
cells: string[];
/** the bar in parts (in % of the bar), each with what it says when hovered */
segments?: { width: number; color: string; title: string }[];
/** said in place of the bar (a row with nothing to draw) */
none?: string;
}
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');
/** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) {
case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {};
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) && !hidden.includes(c));
const all = [
...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 {
head: ['n', '%'],
rows: all.map(({ code, label, color }) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
note: hiddenNote(mode, of),
};
}
case 'shares': {
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 r = of(mode.measure);
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
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': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative']), mode.colors?.[s]];
}),
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
mode.tint,
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
mode.tint,
);
}
case 'split': {
const { numerator = 0, denominator = 0 } = of(mode.measure)?.populations ?? {};
if (!denominator) return undefined;
const parts: [string, number][] = [
[mode.yes, numerator],
[mode.no, denominator - numerator],
];
return {
head: ['n', '%'],
rows: parts.map(([label, n], i) => ({
label,
color: mode.colors?.[i],
width: (100 * n) / denominator,
marks: [],
cells: [`${n}`, pct(n, denominator)],
})),
};
}
case 'outcomes': {
const r = of(mode.measure);
const units = r?.strata[mode.stratum] ?? {};
const cells = r?.strata[`${mode.stratum}-category`] ?? {};
if (!Object.keys(units).length) return undefined;
const graded = (i: number) => !['no_biopsy', 'no_data'].includes(mode.results[i].code);
return {
head: ['Pacientes', ...mode.results.map((x) => x.label), '% maligno'],
legend: mode.results.map(({ label, color }) => ({ label, color })),
rows: mode.rows.map(({ code, label }) => {
const n = size(units[code]);
const by = mode.results.map((x) => size(cells[`${code}|${x.code}`]));
const den = by.reduce((t, k, i) => t + (graded(i) ? k : 0), 0);
const bad = by.reduce(
(t, k, i) => t + (mode.malignant.includes(mode.results[i].code) ? k : 0),
0,
);
return {
label,
width: 100,
marks: [],
none: n ? undefined : 'Sin pacientes en el periodo',
segments: mode.results.map((x, i) => ({
width: n ? (100 * by[i]) / n : 0,
color: x.color,
title: `${x.label}: ${by[i]} de ${n} (${pct(by[i], n)})`,
})),
cells: [
`${n}`,
...by.map((k) => (n ? `${k}` : '—')),
n
? den
? `${bad}/${den} (${pct(bad, den)})`
: by[mode.results.findIndex((x) => x.code === 'no_data')]
? 'Sin biopsias clasificables'
: 'Sin biopsias'
: '—',
],
};
}),
};
}
default:
return 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, color]) => ({
label,
color,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = { score?: number; low?: number; high?: number };
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
@@ -1,76 +0,0 @@
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
@@ -1,88 +0,0 @@
/** 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';
+157
View File
@@ -0,0 +1,157 @@
import { describe, expect, it } from 'vitest';
import {
BIOPSY_REPORTS,
CYTOLOGY_REPORTS,
distribution,
durationMax,
durationRows,
HPV_REPORTS,
icdRows,
requests,
withoutHidden,
} from './cacu-results';
import { PAGES } from './pages';
import { PPV_NOTES, Reading, STRATA, name } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: {
category: Object.fromEntries(
Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
describe('distributions of reports', () => {
it('counts HPV reports and keeps inconsistent and zero categories', () => {
const d = distribution(
report(4, { negative: 2, positive_16: 1, inconsistent: 1 }),
HPV_REPORTS,
)!;
expect(d.total).toBe(4);
expect(d.rows.map((r) => r.count)).toEqual([2, 1, 0, 0, 0, 0, 1]);
expect(d.outside).toBe(0);
});
it('leaves what the table does not list outside it and says how much is without data', () => {
const d = distribution(
report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }),
BIOPSY_REPORTS,
)!;
expect(d.total).toBe(3);
expect(d.noData).toBe(1);
expect(d.outside).toBe(2);
});
it('does not invent a report: missing, or counts that do not add up, draw nothing; zero is zero', () => {
expect(distribution(undefined, HPV_REPORTS)).toBeUndefined();
expect(distribution(report(2, { normal: 1 }), BIOPSY_REPORTS)).toBeUndefined();
expect(distribution(report(0, {}), HPV_REPORTS)).toMatchObject({
total: 0,
max: 0,
outside: 0,
});
});
});
describe('the categories a table leaves out', () => {
const hidden = ['positive_incomplete', 'inconsistent'];
it('lists the rest, keeps the total and the percentage denominator, and counts what it hides', () => {
const d = distribution(
report(10, { negative: 5, positive_16: 2, positive_incomplete: 2, inconsistent: 1 }),
HPV_REPORTS,
)!;
const v = withoutHidden(d, hidden);
expect(d.total).toBe(10);
expect(v.shown.map((r) => r.code)).not.toContain('positive_incomplete');
expect(v.shown.map((r) => r.code)).not.toContain('inconsistent');
expect(v.hiddenCount).toBe(3);
expect(v.max).toBe(5);
// nothing hidden: the rows are all of them and the count is zero (the page adds no note)
expect(withoutHidden(d).shown).toHaveLength(HPV_REPORTS.length);
expect(withoutHidden(d).hiddenCount).toBe(0);
});
it('is the page choice for HPV; cytology and biopsy keep every category', () => {
const results = PAGES['cacu'].clinical.find((s) => s.kind === 'results')!;
if (results.kind !== 'results') throw new Error('no joint card');
expect(results.hpv.hide).toEqual(hidden);
expect(results.cytology.hide).toBeUndefined();
expect(results.biopsy.hide).toBeUndefined();
expect(CYTOLOGY_REPORTS.map((r) => r[0])).toEqual([
'NILM',
'ASC-US',
'LSIL',
'ASC-H',
'HSIL',
'CIS',
]);
});
});
describe('biopsy requests', () => {
it('reads every state of the request and keeps them apart from patients', () => {
const r = requests(
report(9, { high_grade: 3, below_high_grade: 2, pending: 2, no_grade: 1, ambiguous: 1 }),
)!;
expect(r).toMatchObject({ total: 9, high: 3, below: 2, pending: 2, noGrade: 1, ambiguous: 1 });
expect(r.unclassified + r.inconsistent).toBe(0);
});
it('is none for a missing, failed or inconsistent report, and a zero total is a real zero', () => {
expect(requests(undefined)).toBeUndefined();
expect(requests({ ...report(1, { pending: 1 }), error: true })).toBeUndefined();
expect(requests(report(3, { pending: 1 }))).toBeUndefined();
expect(requests(report(0, {}))?.total).toBe(0);
});
});
describe('ICD-10 breakdown', () => {
it('lists each code with its median and quartiles, most frequent first', () => {
const r: Reading = {
populations: { 'initial-population': 3, 'measure-observation': 3 },
strata: {
diagnosis_code: {
C53: { 'measure-observation': 2 },
sin_codigo: { 'measure-observation': 1 },
},
},
stratumScores: {
diagnosis_code: {
C53: { median: 30, low: 25, high: 40 },
sin_codigo: { median: 12 },
},
},
};
expect(icdRows(r)).toEqual([
{ label: 'C53', count: 2, median: 30, low: 25, high: 40 },
{ label: 'Sin código disponible', count: 1, median: 12 },
]);
expect(icdRows(undefined)).toEqual([]);
});
});
describe('route by steps', () => {
const at = (score?: number, n = 4, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
it('keeps every step, tells absent from zero and scales from zero to the largest quartile', () => {
const rows = durationRows([
{ label: 'a', r: at(0, 3, 0, 2) },
{ label: 'b', r: at(undefined) },
{ label: 'c', r: at(13, 4, 9, 41) },
{ label: 'd', r: undefined },
]);
expect(rows.map((r) => r.label)).toEqual(['a', 'b', 'c', 'd']);
expect(rows[0]).toMatchObject({ median: 0, observations: 3, low: 0, high: 2 });
expect(rows[1].median).toBeUndefined();
expect(rows[1].observations).toBeUndefined();
expect(rows[3].median).toBeUndefined();
expect(durationMax(rows)).toBe(41);
expect(durationMax(durationRows([{ label: 'x', r: undefined }]))).toBe(0);
});
});
+167
View File
@@ -0,0 +1,167 @@
import type { Reading } from './measures';
/** One category of a distribution: its code in the report, its words and its colour. */
export type DistRow = readonly [code: string, label: string, color: string];
/** A distribution drawn as a table with a bar per category (CaCu's results of HPV and biopsy). */
export interface Distribution {
rows: { code: string; label: string; color: string; count: number }[];
/** units in the categories shown */
total: number;
/** units of the period that are in none of them */
outside: number;
max: number;
/** units the report counts as "no data" (no grade, no result) */
noData: number;
}
/** The categories of a report's `category` stratum, as counts of units. The strata must add up
* to the population: otherwise the report is not trusted and nothing is drawn. A category the
* report does not list is a zero, a missing report is not. */
export function distribution(
reading: Reading | undefined,
categories: readonly DistRow[],
): Distribution | undefined {
const cells = reading?.strata['category'];
const population = reading?.populations['initial-population'];
if (!cells || population === undefined) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (
counts.some((n) => n === undefined || !Number.isInteger(n) || n < 0) ||
counts.reduce((a, b) => a + b, 0) !== population
)
return undefined;
const rows = categories.map(([code, label, color]) => ({
code,
label,
color,
count: cells[code]?.['initial-population'] ?? 0,
}));
const total = rows.reduce((sum, row) => sum + row.count, 0);
return {
rows,
total,
outside: population - total,
max: Math.max(0, ...rows.map((row) => row.count)),
noData: cells['no_data']?.['initial-population'] ?? 0,
};
}
/** Cytology results by Bethesda category (one sample per patient, the latest valid). */
export const CYTOLOGY_REPORTS: readonly DistRow[] = [
['NILM', 'Normal', '#408651'],
['ASC-US', 'ASC-US', '#2778B8'],
['LSIL', 'LIEBG', '#B19525'],
['ASC-H', 'ASC-H', '#7955B1'],
['HSIL', 'LIEAG', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
];
/** The rows a table lists once some categories are left out of it: the total, the percentages and
* the units outside stay as the report gives them (nothing is recomputed); only the rows, the
* bars' scale and a count of what is not listed change. */
export function withoutHidden(d: Distribution, hide: readonly string[] = []) {
const shown = d.rows.filter((r) => !hide.includes(r.code));
return {
shown,
max: Math.max(0, ...shown.map((r) => r.count)),
hiddenCount: d.rows.filter((r) => hide.includes(r.code)).reduce((n, r) => n + r.count, 0),
};
}
/** HPV reports by genotype (one report per patient and sample date). */
export const HPV_REPORTS: readonly DistRow[] = [
['negative', 'Negativo', '#42a77e'],
['positive_16', 'Positivo 16 exclusivamente', '#df8640'],
['positive_18', 'Positivo 18 exclusivamente', '#c29c42'],
['positive_16_18', 'Positivo 16 y 18', '#c24269'],
['positive_other', 'Positivo sin detección de 16/18', '#a8c243'],
['positive_incomplete', 'Positivo con genotipificación incompleta', '#9c42c2'],
['inconsistent', 'No clasificable o inconsistente', '#687786'],
];
/** Biopsy reports by the grade they state. */
export const BIOPSY_REPORTS: readonly DistRow[] = [
['normal', 'Normal', '#408651'],
['LSIL', 'LIEBG (CIN 1)', '#B19525'],
['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'],
['CIS', 'Carcinoma in situ', '#AA394D'],
['carcinoma', 'Carcinoma invasor', '#8D4C79'],
];
/** The ICD-10 codes of the diagnosis notes, each with its median and quartiles of days from the
* sample to the diagnosis (an exploratory grouping by the dates that link them). */
export function icdRows(reading: Reading | undefined) {
const scores = reading?.stratumScores?.['diagnosis_code'] ?? {};
return Object.entries(scores)
.map(([label, score]) => ({
label: label
.replace('sin_codigo', 'Sin código disponible')
.replace('ambiguo', 'Diagnóstico ambiguo'),
count: reading?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0,
...score,
}))
.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
}
/** The biopsy requests on record by their state at the cut-off; they are requests, not patients. */
export interface Requests {
total: number;
high: number;
below: number;
pending: number;
noGrade: number;
unclassified: number;
inconsistent: number;
ambiguous: number;
}
/** None when the report is missing, errored or does not add up (the page then says so). */
export function requests(reading: Reading | undefined): Requests | undefined {
const total = reading?.populations['initial-population'];
const cells = reading?.strata['category'];
if (!reading || reading.error || total === undefined || !cells) return undefined;
const counts = Object.values(cells).map((cell) => cell['initial-population']);
if (
!Number.isInteger(total) ||
total < 0 ||
counts.some((n) => !Number.isInteger(n) || n < 0) ||
counts.reduce((sum, n) => sum + n, 0) !== total
)
return undefined;
const of = (key: string) => cells[key]?.['initial-population'] ?? 0;
return {
total,
high: of('high_grade'),
below: of('below_high_grade'),
pending: of('pending'),
noGrade: of('no_grade'),
unclassified: of('unclassified'),
inconsistent: of('inconsistent'),
ambiguous: of('ambiguous'),
};
}
/** One row of a duration table: the median days, how many measurements and the quartiles. A
* step with no median keeps its row and says nothing (absent is not zero). */
export interface DurationRow {
label: string;
median?: number;
observations?: number;
low?: number;
high?: number;
}
export function durationRows(steps: { label: string; r: Reading | undefined }[]): DurationRow[] {
return steps.map(({ label, r }) => ({
label,
median: r?.score,
observations: r?.score === undefined ? undefined : r.populations['measure-observation'],
low: r?.score === undefined ? undefined : r.low,
high: r?.score === undefined ? undefined : r.high,
}));
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
-19
View File
@@ -1,19 +0,0 @@
/** The ICD-10 codes a cervical diagnosis is dated by (core.cacu DIAGNOSIS_ICD10). */
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { requestsAlternate } from './confirmation';
import { Reading } from './measures';
const report = (population: number, counts: Record<string, number>): Reading => ({
populations: { 'initial-population': population },
strata: {
category: Object.fromEntries(
Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]),
),
},
});
describe('biopsy requests as a reading of the biopsy card', () => {
it('keeps the request denominator, bars and secondary counts of the old card', () => {
const a = requestsAlternate(report(13, { high_grade: 9, below_high_grade: 4 }), true);
expect(a.score).toBe('69.2 %');
expect(a.detail).toContain('9 de 13 solicitudes registradas (no pacientes)');
expect(a.rows.map((r) => [r.label, r.numerator, r.denominator])).toEqual([
['LIEAG o más', 9, 13],
['Menor que LIEAG', 4, 13],
]);
expect(a.lines[0]).toContain('Pendientes: 0 · Sin grado: 0 · No clasificables: 0');
expect(a.note).toContain('no se pide un corte histórico (as-of)');
});
it('shows pending and ungraded requests in the denominator, not as a result', () => {
const a = requestsAlternate(
report(10, { high_grade: 2, below_high_grade: 1, pending: 4, no_grade: 2, ambiguous: 1 }),
true,
);
expect(a.rows[0].denominator).toBe(10);
expect(a.lines[0]).toContain('Pendientes: 4 · Sin grado: 2');
expect(a.lines[0]).toContain('ambiguos: 1');
});
it('tells no records (a zero) from a missing, failed or inconsistent report', () => {
expect(requestsAlternate(report(0, {}), true).message).toContain('denominador 0');
expect(requestsAlternate(report(0, {}), true).score).toBe('0 solicitudes');
expect(requestsAlternate(undefined, true).message).toContain('No disponible para este periodo');
expect(requestsAlternate(undefined, false).message).toContain('no publicada');
const failed = requestsAlternate({ ...report(1, { pending: 1 }), error: true }, true);
expect(failed.alert).toBe(true);
expect(requestsAlternate(report(5, { pending: 1 }), true).alert).toBe(true);
});
});
+73
View File
@@ -0,0 +1,73 @@
import { requests } from './cacu-results';
import { Reading } from './measures';
import { PpvAlternate } from './ppv';
/** The biopsy requests as one more reading of the biopsy PPV card. They are requests, not
* patients, and the denominator is every request on record (pending and ungraded ones too); the
* histological threshold is high grade (LIEAG or more), not the PPV's LIEBG or more. */
export function requestsAlternate(reading: Reading | undefined, published: boolean): PpvAlternate {
const base = {
label: 'Solicitudes de biopsia',
title: 'Confirmación por solicitudes de biopsia registradas',
note:
'La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones. ' +
'Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud; no se pide un corte ' +
'histórico (as-of) porque la medida no lo admite.',
caption:
'Solicitudes, no pacientes: cada barra cuenta las solicitudes con ese resultado sobre todas las solicitudes ' +
'registradas, incluidas las pendientes y las que no tienen grado.',
rows: [],
lines: [],
};
const without = (message: string, score = 'Sin dato', alert = false): PpvAlternate => ({
...base,
score,
detail: '',
message,
alert,
});
if (!published) return without('No disponible: medida no publicada por el servidor.');
if (reading?.error)
return without('No se pudo consultar las solicitudes de biopsia.', 'Sin dato', true);
if (!reading) return without('No disponible para este periodo.');
const r = requests(reading);
if (!r)
return without(
'Los datos de solicitudes recibidos están incompletos o son inconsistentes.',
'Sin dato',
true,
);
if (!r.total)
return without(
'Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).',
'0 solicitudes',
);
const share = (n: number) => (100 * n) / r.total;
return {
...base,
score: `${share(r.high).toFixed(1)} %`,
detail: `${r.high} de ${r.total} solicitudes registradas (no pacientes) con histología LIEAG o más.`,
rows: [
{
code: 'high_grade',
label: 'LIEAG o más',
color: '#CE4778',
numerator: r.high,
denominator: r.total,
percent: share(r.high),
},
{
code: 'below_high_grade',
label: 'Menor que LIEAG',
color: '#8FA7BB',
numerator: r.below,
denominator: r.total,
percent: share(r.below),
},
],
lines: [
`Pendientes: ${r.pending} · Sin grado: ${r.noGrade} · No clasificables: ${r.unclassified} · ` +
`Fechas inconsistentes: ${r.inconsistent} · Registros fusionados ambiguos: ${r.ambiguous}.`,
],
};
}
-55
View File
@@ -1,55 +0,0 @@
import { durationMax, durationRows } from './durations';
import { Reading } from './measures';
const reading = (score?: number, n = 0, low?: number, high?: number): Reading => ({
populations: { 'measure-observation': n },
score,
low,
high,
strata: {},
});
describe('durationRows', () => {
const reads: Record<string, Reading> = {
A: reading(0, 3, 0, 1),
B: reading(6, 20, 4, 8),
C: reading(undefined, 0),
};
const rows = durationRows(
[
{ label: 'zero', measure: 'A' },
{ label: 'value', measure: 'B' },
{ label: 'nothing measured', measure: 'C' },
{ label: 'no report', measure: 'D' },
{ label: 'not in the catalog', measure: 'E' },
{ label: 'no measure' },
],
(m) => reads[m],
(m) => m !== 'E',
);
it('keeps a real zero as a value', () => {
expect(rows[0]).toEqual({
label: 'zero',
status: 'value',
median: 0,
observations: 3,
low: 0,
high: 1,
});
});
it('tells no measurements from an unpublished measure', () => {
expect(rows.map((r) => r.status)).toEqual([
'value',
'value',
'empty',
'empty',
'unpublished',
'unpublished',
]);
});
it('scales from zero to the largest median or third quartile', () => {
expect(durationMax(rows)).toBe(8);
expect(durationMax([])).toBe(0);
});
});
-46
View File
@@ -1,46 +0,0 @@
import { Reading } from './measures';
/** One step of a route: its name and the measure that times it. A step with no measure is
* not published yet. */
export interface RouteStep {
label: string;
measure?: string;
}
/** One row of a duration table: the median days, how many measurements and the quartiles.
* `empty` (published, nothing measured in the period) is not `unpublished` (no measure), and
* neither is a zero: a median of 0 days is a value. */
export interface DurationRow {
label: string;
status: 'value' | 'empty' | 'unpublished';
median?: number;
observations?: number;
low?: number;
high?: number;
}
/** The rows of a route in one reading; every step keeps its row. `published` says which
* measures the catalog has. */
export function durationRows(
steps: RouteStep[],
read: (measure: string) => Reading | undefined,
published: (measure: string) => boolean,
): DurationRow[] {
return steps.map(({ label, measure }) => {
if (!measure || !published(measure)) return { label, status: 'unpublished' };
const r = read(measure);
if (r?.score === undefined) return { label, status: 'empty' };
return {
label,
status: 'value',
median: r.score,
observations: r.populations['measure-observation'],
low: r.low,
high: r.high,
};
});
}
/** The scale of a table of durations, from zero: the largest median or third quartile shown. */
export const durationMax = (rows: DurationRow[]): number =>
Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0)));
+22 -38
View File
@@ -1,5 +1,4 @@
import { type Figure, PALETTE } from '../plot';
import { reconciles } from './bars';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
@@ -91,66 +90,51 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur
};
}
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
/** A result's share inside each clinical scenario (the report's `<stratum>-category` cells):
* each bar is 100 % of the patients of that scenario with a result in the catalogue, and its
* label says how many they are. Compact: a one-line legend above and thin bars. */
export function scenarioBars(
r: Reading,
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 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) =>
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 scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const y = order
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
: scenarios.map(label);
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((s, i) => `${label(s)}<br>n = ${count(totals[i])}`);
const share = (s: string, i: number, c: string) => (totals[i] ? (100 * n(s, c)) / totals[i] : 0);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
x: scenarios.map((s, i) => share(s, i, c.code)),
customdata: scenarios.map((s) => n(s, c.code)),
text: scenarios.map((s, i) =>
share(s, i, c.code) >= 12 ? `${percent(share(s, i, c.code))} %` : '',
),
textposition: 'inside',
insidetextanchor: 'middle',
textangle: 0,
textfont: { color: '#ffffff', size: 11 },
marker: { color: c.color },
hovertemplate: `${c.label}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
})) as Partial<Plotly.Data>[],
layout: {
barmode: 'stack',
bargap: 0.35,
showlegend: false, // the page draws the legend, which wraps on a narrow screen
margin: { t: 8, r: 8, b: 40, l: 8 },
xaxis: {
title: {
text: order
? options.ofAll
? '% de los reportes del grupo'
: '% de pacientes con resultado'
: '% de pacientes del escenario con resultado',
},
title: { text: '% de las pacientes del escenario con resultado', font: { size: 11 } },
ticksuffix: ' %',
range: [0, 100.5],
dtick: 20,
dtick: 25,
},
yaxis: {
type: 'category',
-52
View File
@@ -1,52 +0,0 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
const HEAD = [
'Paciente',
'CURP',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
'LIEAG+',
'Cáncer',
'Días a diagnóstico',
];
/** A cytology's result, or why it has none. */
export function cytologyResult(c: NonNullable<Row['cytology']>): string {
if (c.result) return name(c.result);
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
/** The follow-up list as a table to save, with the query it answers. */
export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
return {
title: 'Resultados de seguimiento',
query: [...query, ['Registros', `${rows.length}`]],
head: HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
`${r.age ?? NONE}`,
name(r.status),
r.stages
.filter((s) => s.state !== 'unknown')
.map((s) => `${s.label}: ${s.day ?? STATES[s.state]}`)
.join('\n'),
r.cytology ? `${cytologyResult(r.cytology)} (${r.cytology.date})` : NONE,
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'} (${r.hpv.date})` : NONE,
r.biopsy ? `${name(r.biopsy.histology ?? '') || 'Sin grado'} (${r.biopsy.date})` : NONE,
percent(r.risk.cin2),
percent(r.risk.cancer),
`${r.daysToDiagnosis ?? NONE}`,
]),
};
}
+50 -13
View File
@@ -1,8 +1,56 @@
import type { RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, windowStart, ageAt, bornFor } from './follow-up';
import '@angular/compiler';
import { describe, expect, it } from 'vitest';
import type { Patient, RiskAssessment } from 'fhir/r4';
import {
ageGroup,
currentRisk,
exactAge,
patientLabel,
patientName,
rows,
windowStart,
} from './follow-up';
import { periods } from './measures';
describe('follow-up list', () => {
it('uses synthetic FHIR names consistently and keeps the patient id as fallback', () => {
const patient: Patient = {
resourceType: 'Patient',
id: 'abcdef123456',
name: [{ text: ' Ana Ejemplo ' }],
};
const page = {
resourceType: 'Bundle' as const,
type: 'searchset' as const,
entry: [{ resource: patient, search: { mode: 'match' as const } }],
};
expect(rows(page, '2026-01-01', '2026-11-27', 5)[0].name).toBe('Ana Ejemplo');
expect(patientLabel(patient)).toBe('Ana Ejemplo');
expect(
patientName({ ...patient, name: [{ given: ['Ana', 'María'], family: 'Ejemplo' }] }),
).toBe('Ana María Ejemplo');
expect(patientLabel({ ...patient, name: [{ text: ' ' }] })).toBe('abcdef1234');
});
it('calculates completed years only from valid full dates', () => {
expect(exactAge('1980-11-23', '2026-11-22')).toBe(45);
expect(exactAge('1980-11-23', '2026-11-23')).toBe(46);
expect(exactAge('2000-02-29', '2025-02-28')).toBe(24);
expect(exactAge('2000-02', '2026-01-01')).toBeUndefined();
expect(exactAge('2001-02-29', '2026-01-01')).toBeUndefined();
expect(exactAge('2027-01-01', '2026-01-01')).toBeUndefined();
});
it('keeps a missing prediction separate from zero', () => {
const risk = (p?: number): RiskAssessment => ({
resourceType: 'RiskAssessment',
status: 'final',
subject: {},
occurrenceDateTime: '2026-01-01',
method: { coding: [{ code: 'cacu.cin2_pim' }] },
prediction: [{ probabilityDecimal: p, whenRange: { high: { value: 5 } } }],
});
expect(currentRisk([risk()], 'cin2', 5)).toBeUndefined();
expect(currentRisk([risk(0)], 'cin2', 5)).toBe(0);
});
it('starts the window the day after the same day months before (core.follow_up)', () => {
expect(windowStart('2026-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
@@ -45,14 +93,3 @@ describe('follow-up list', () => {
]);
});
});
describe('ages', () => {
it('ask for the birth dates whose completed years fall in the range', () => {
expect(bornFor('2026-06-30', 36, 40)).toEqual(['le1990-06-30', 'gt1985-06-30']);
expect(bornFor('2026-06-30', null, null)).toEqual([]);
expect(bornFor('2024-02-29', 1, null)).toEqual(['le2023-02-28']);
expect([ageAt('1990-06-30', '2026-06-30'), ageAt('1990-07-01', '2026-06-30')]).toEqual([
36, 35,
]);
});
});
+50 -36
View File
@@ -1,6 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
import { route, Stage } from '../paciente/stages';
import { routeFacts, StageFacts } from '../paciente/stages';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
@@ -10,8 +10,8 @@ export interface Row {
status: string;
ageGroup: string;
age?: number;
stages: Stage[];
cytology?: { date: string; result?: string; adequacy?: string };
stageFacts: StageFacts;
cytology?: { date: string; reportDate?: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string };
@@ -20,6 +20,42 @@ export interface Row {
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
/** Prefer the supplied FHIR display text, then a structured name, then the next name. */
export function patientName(patient: Patient | undefined): string | undefined {
for (const name of patient?.name ?? []) {
const text = name.text?.trim();
if (text) return text;
const parts = [...(name.given ?? []), name.family ?? '']
.map((part) => part.trim())
.filter(Boolean);
if (parts.length) return parts.join(' ');
}
return undefined;
}
export function patientLabel(patient: Patient | undefined): string {
return patientName(patient) ?? patient?.id?.slice(0, 10) ?? 'No disponible';
}
/** Completed years on a full, valid calendar date; partial dates are unknown. */
export function exactAge(
birth: string | undefined,
cutoff: string | undefined,
): number | undefined {
const parse = (text?: string): [number, number, number] | undefined => {
if (!text || !/^\d{4}-\d{2}-\d{2}$/.test(text)) return undefined;
const [y, m, d] = text.split('-').map(Number);
if (y < 1 || m < 1 || m > 12 || d < 1) return undefined;
const leap = y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0);
if (d > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]) return undefined;
return [y, m, d];
};
const b = parse(birth),
c = parse(cutoff);
if (!b || !c || birth! > cutoff!) return undefined;
return c[0] - b[0] - (c[1] < b[1] || (c[1] === b[1] && c[2] < b[2]) ? 1 : 0);
}
const AGE_GROUPS: [number, number][] = [
[25, 34],
[35, 44],
@@ -27,36 +63,15 @@ const AGE_GROUPS: [number, number][] = [
[55, 64],
];
/** Completed years at a day. */
export function ageAt(birth: string | undefined, at: string): number | undefined {
if (!birth) return undefined;
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
return y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
}
/** The birth dates of who has completed between `from` and `to` years at a day, as FHIR's
* `birthdate` parameter. */
export function bornFor(at: string, from: number | null, to: number | null): string[] {
const back = (years: number) => `${Number(at.slice(0, 4)) - years}${at.slice(4)}`;
return [
...(from === null ? [] : [`le${valid(back(from))}`]),
...(to === null ? [] : [`gt${valid(back(to + 1))}`]),
];
}
/** February 29th in a year without one: the 28th. */
const valid = (day: string) =>
day.endsWith('-02-29') && new Date(`${day}T00:00:00Z`).getUTCMonth() !== 1
? `${day.slice(0, 8)}28`
: day;
export function ageGroup(
birth: string | undefined,
at: string,
groups: [number, number][] = AGE_GROUPS,
): string {
const age = ageAt(birth, at);
if (age === undefined) return 'Sin dato';
if (!birth) return 'Sin dato';
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const found = groups.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`;
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
@@ -73,7 +88,7 @@ export function currentRisk(
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) =>
(r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon)
.filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
.map((p) => ({ r, p })),
);
if (!mine.length) return undefined;
@@ -82,9 +97,7 @@ export function currentRisk(
.sort()
.at(-1);
return Math.max(
...mine
.filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal ?? 0),
...mine.filter((x) => x.r.occurrenceDateTime === latest).map((x) => x.p.probabilityDecimal!),
);
}
@@ -123,14 +136,15 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return {
patient,
name: patient.name?.[0]?.text,
name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
age: ageAt(patient.birthDate, cutoff),
stages: route(last, cutoff),
age: exactAge(patient.birthDate, cutoff),
stageFacts: routeFacts(last),
cytology: last && {
date: last.effectiveDateTime!,
reportDate: ext(last, 'report-date')?.valueDate,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
},
@@ -213,7 +227,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1);
return {
patient,
name: patient.name?.[0]?.text,
name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
+79 -44
View File
@@ -44,14 +44,17 @@ export function periodTypes(measure: Measure): PeriodType[] {
/** What one report says: its counts, its score and interval, and its strata. */
export interface Reading {
/** The server refused or failed the report (a measure that was asked for, not an empty one). */
error?: boolean;
populations: Record<string, number>;
score?: number;
low?: number;
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
/** A stratum value's own score (a median and its quartiles). */
scores?: Record<string, Record<string, { score?: number; low?: number; high?: number }>>;
/** A stratum's own score by stratifier and value: a median with its quartiles, or a
* proportion with its interval, whichever the report publishes. */
stratumScores?: Record<string, Record<string, { median: number; low?: number; high?: number }>>;
}
function counts(group: {
@@ -67,7 +70,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined;
const score = group.measureScore;
const strata: Reading['strata'] = {};
const scores: NonNullable<Reading['scores']> = {};
const stratumScores: NonNullable<Reading['stratumScores']> = {};
for (const s of group.stratifier ?? []) {
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
@@ -79,13 +82,18 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
counts(x),
]),
);
for (const { value, measureScore: own } of s.stratum ?? [])
if (own)
(scores[name] ??= {})[value?.text ?? ''] = {
score: own.value,
low: ext(own, 'q1')?.valueDecimal,
high: ext(own, 'q3')?.valueDecimal,
};
stratumScores[name] = Object.fromEntries(
(s.stratum ?? [])
.filter((x) => x.measureScore?.value !== undefined)
.map((x) => [
x.value?.text ?? '',
{
median: x.measureScore!.value!,
low: (ext(x.measureScore, 'q1') ?? ext(x.measureScore, 'ic-bajo'))?.valueDecimal,
high: (ext(x.measureScore, 'q3') ?? ext(x.measureScore, 'ic-alto'))?.valueDecimal,
},
]),
);
}
return {
populations: counts(group),
@@ -94,7 +102,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit,
strata,
scores,
stratumScores,
};
}
@@ -133,22 +141,17 @@ export const LABELS: Record<string, string> = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Detección inicial',
subsequent: 'Detección subsecuente',
'ASCUS+': 'Citología ASC-US o mayor',
'LSIL+': 'Citología LIEBG o mayor',
'HSIL+': 'Citología LIEAG o mayor',
'LIEBG+': 'Histología LIEBG o mayor',
'LIEAG+': 'Histología LIEAG o mayor',
initial: 'Tamizaje inicial',
subsequent: 'Tamizaje subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
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',
hpv_16: 'Positivo para VPH 16',
hpv_18: 'Positivo para VPH 18',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
@@ -161,14 +164,43 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente',
referral_cytology: 'Citología previa asociada por fechas',
referral_hpv: 'VPH de la citología previa asociada por fechas',
histology_level: 'Nivel de histología confirmado',
screening_round: 'Tamizaje inicial o subsecuente',
result_initial: 'Resultado en tamizaje inicial',
result_subsequent: 'Resultado en tamizaje subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
hpv_initial: 'VPH en tamizaje inicial',
hpv_subsequent: 'VPH en tamizaje subsecuente',
};
/** What the referral PPVs are: the records show procedures, not issued referrals, and the
* previous cytology is linked by dates. */
export const PPV_NOTES: Record<string, { title: string; note: string }> = {
CACU_VPP_COLPOSCOPIA: {
title: 'VPP tras colposcopía registrada',
note:
'De las pacientes con colposcopía registrada en el periodo (puede inferirse de notas clínicas), ' +
'las que tienen histología LIEBG o mayor. Se muestra la citología previa más reciente en los 365 ' +
'días anteriores: es una asociación por fechas, no un vínculo clínico confirmado ni una referencia emitida.',
},
CACU_VPP_BIOPSIA: {
title: 'VPP tras biopsia registrada',
note:
'De las pacientes con biopsia reportada en el periodo, las que tienen histología LIEBG o mayor. ' +
'La citología previa es una asociación por fechas, no un vínculo clínico confirmado ni una referencia ' +
'emitida. Su denominador difiere del de las solicitudes de biopsia registradas.',
},
CACU_VPH: {
title: 'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
note:
'Una paciente por periodo, por su última muestra con resultado de VPH, aunque la citología no tenga ' +
'resultado. Es distinto de los reportes de VPH por genotipo, que cuentan reportes, no pacientes.',
},
};
export const measureTitle = (m: { name?: string; title?: string }) =>
PPV_NOTES[m.name ?? '']?.title ?? m.title ?? m.name ?? '';
export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
@@ -183,14 +215,14 @@ export function formatScore(measure: Measure, r: Reading | undefined): string {
}
}
export function detail(measure: Measure, r: Reading | undefined, unit = 'pacientes'): string {
export function detail(measure: Measure, r: Reading | undefined): string {
if (!r) return '';
const p = r.populations;
switch (scoring(measure)) {
case 'proportion':
return r.score === undefined
? `Sin ${unit} en el periodo.`
: `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
? 'Sin pacientes en el periodo.'
: `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
case 'continuous-variable':
return r.score === undefined
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
@@ -203,23 +235,15 @@ 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',
/** 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[];
export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure {
let labels: string[], values: number[];
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 {
@@ -231,7 +255,7 @@ export function donut(
values,
sort: false,
textinfo: 'value+percent',
marker: { colors: codes.map((c, i) => colors?.[c] ?? PALETTE[i % PALETTE.length]) },
marker: { colors: PALETTE },
},
],
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
@@ -257,6 +281,17 @@ export function strataBars(measure: Measure, r: Reading, stratifier: string): Fi
y: cells.map(([v]) => name(v)),
x: values,
marker: { color: PALETTE[0] },
...(proportion
? {
text: cells.map(([, c]) =>
c['denominator']
? `${c['numerator'] ?? 0} de ${c['denominator']}`
: 'sin pacientes',
),
textposition: 'auto' as const,
hovertemplate: '%{y}<br>%{x:.1f} % (%{text})<extra></extra>',
}
: {}),
},
],
layout: {
-346
View File
@@ -1,346 +0,0 @@
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';
const ROSE = '#C24269';
/** Bethesda results as the old app grouped and coloured them. */
const CYTOLOGY: Catalog = {
groups: [
{ id: 'normal', label: 'Sin anomalía', color: OLIVE },
{ id: 'abnormal', label: 'Anormal', color: ROSE },
],
categories: [
{ 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' },
],
};
/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */
const BIOPSY: Catalog = {
groups: [
{ id: 'low', label: 'Menor que LIEAG', color: OLIVE },
{ id: 'high', label: 'LIEAG o más', color: ROSE },
],
categories: [
{ 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: 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: 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'];
const ROUND_MEANING =
'«Detección inicial»: primera vez en la vida y sin colposcopía ni tratamiento a la toma. ' +
'«Detección subsecuente»: con detección previa registrada, o ya con colposcopía o tratamiento a la toma. ' +
'«Sin dato»: sin detección previa registrada y sin colposcopía ni tratamiento. ';
const CYTOLOGY_BARS =
'Cada barra suma 100 % de las pacientes del grupo con resultado citológico (n indica cuántas son).';
const POSITIVE_MEANING =
'«Positivo»: VPH de alto riesgo positivo con los genotipos 16 y 18 reportados negativos; los positivos para 16, 18 o ambos se muestran aparte.';
/** 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,
caption: { age: string; status: string; round: string },
more: { ofAll?: boolean; hidden?: { codes: string[]; unit: string } } = {},
): Mode[] =>
[
{ label: BY_AGE, stratum: 'age_group', order: AGE_GROUPS, caption: caption.age },
{ label: BY_STATUS, stratum: 'follow_up_status', order: STATUSES, caption: caption.status },
{ label: BY_ROUND, stratum: 'round', order: ROUNDS, caption: caption.round, 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',
title,
headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ 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'],
},
{
kind: 'shares',
label: 'VPH previo',
caption: 'Los grupos se traslapan.',
measure,
stratum: 'hpv',
colors: HPV_COLORS,
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
},
{
kind: 'shares',
label: 'Nivel de histología',
measure,
stratum: 'level',
colors: PPV_LEVEL_COLORS,
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
},
{
kind: 'shares',
label: 'Por detección inicial y subsecuente',
caption: ROUND_CAPTION,
measure,
stratum: 'round',
colors: ROUND_COLORS,
order: ROUNDS,
complete: true,
},
...more,
],
});
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
export const CACU: Page = {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempos de la ruta del tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
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' },
],
},
{
kind: 'days',
tint: TINT,
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
],
},
{
kind: 'days-by',
tint: TINT,
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',
},
],
},
],
clinical: [
{
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 },
...groupViews('CACU_EU7', CYTOLOGY.categories, 'pacientes', {
age:
'Cada paciente cuenta una vez, con su última muestra válida del periodo; la edad es la de la paciente al inicio del periodo. ' +
CYTOLOGY_BARS,
status:
'Cada paciente cuenta una vez, con su última muestra válida del periodo; el estatus es el de la paciente al inicio del periodo. ' +
CYTOLOGY_BARS,
round:
'Cada paciente cuenta una vez, con su última muestra válida del periodo; la detección es la de esa muestra (fecha de toma). ' +
ROUND_MEANING +
CYTOLOGY_BARS +
' Si hay pacientes en «Sin dato», una barra vacía significa que no hay pacientes clasificadas en esa detección según la información disponible.',
}),
],
},
{
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,
hidden: HPV_HIDDEN,
caption: POSITIVE_MEANING,
},
...groupViews(
'CACU_VPH_GENOTIPO',
HPV,
'reportes',
{
age: `Cada barra son los reportes de VPH del grupo de edad de la paciente al inicio del periodo. ${POSITIVE_MEANING}`,
status: `Cada barra son los reportes de VPH del estatus de la paciente al inicio del periodo. ${POSITIVE_MEANING}`,
round: `Cada barra son los reportes de VPH de las muestras de esa detección (fecha de toma). ${ROUND_MEANING}Si hay reportes en «Sin dato», una barra vacía significa que no hay reportes de muestras clasificadas en esa detección según la información disponible. ${POSITIVE_MEANING}`,
},
{ ofAll: true, hidden: HPV_HIDDEN },
),
],
},
{
kind: 'readings',
title: 'Resultados de biopsia cervical',
note: 'Reportes, por fecha de reporte.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories,
},
],
},
],
},
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
choices: [
{
label: 'Colposcopía',
section: ppv(
'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
},
),
},
],
},
],
};
+217 -120
View File
@@ -1,7 +1,3 @@
import type { Mode } from './bars';
import { CACU } from './pages-cacu';
import type { RouteStep } from './durations';
/** A domain's Indicadores page as the old app showed it (tests/fixtures/reference/<domain>/ui):
* the timeliness cards with their own words, then the clinical sections and their figures.
* Measures are named by their code (`Measure.name`). */
@@ -21,41 +17,55 @@ export interface Kpi {
value?: string;
note?: string;
}
/** A card read one mode at a time; `headline` is the measure its score comes from. */
export interface ReadingsCard {
kind: 'readings';
/** A measure's categories as a table with a bar each; say what is counted. */
export interface DistSpec {
title: string;
headline?: string;
/** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string;
note?: string;
modes: Mode[];
/** in a `columns` section with `views`: takes the mode whose label the section's selector chose */
follows?: boolean;
measure: string;
/** what the units are, in the plural */
unit: string;
/** the categories, and which of them to head with a group line */
catalog: readonly (readonly [string, string, string])[];
groups?: { before: string; label: string; codes: string[] }[];
notes: string[];
/** categories left out of the table (their units stay in the total and the percentages) */
hide?: string[];
}
export type Section =
| ReadingsCard
/** A screening route as one compact card: a bar per step with its median, observations and
* quartiles. `sample` reads each step from the sample (its own measure, never a sum of
* 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';
kind: 'route';
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;
/** `measure`: days from the sample to the step; `stepMeasure`: days from the previous step */
steps: { label: string; measure: string; step?: string; stepMeasure?: string }[];
/** the route in three readings: cumulative, step by step, and by the ICD-10 of the diagnosis */
modes?: { icd: 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) */
/** CaCu's joint card: the cytology and HPV distributions side by side, the biopsy's below, and
* the scenario figure as a complement. */
| {
kind: 'choice';
kind: 'results';
title: string;
choices: { label: string; section: ReadingsCard }[];
card?: boolean;
cytology: DistSpec;
hpv: DistSpec;
biopsy: DistSpec;
complement: FigureSpec[];
}
/** A positive predictive value read one way at a time (the whole, or a stratifier). */
| {
kind: 'ppv';
measure: string;
modes: PpvMode[];
/** the heading figures when the measure is not a proportion */
summary?: (reading: Reading | undefined) => { score: string; detail: string };
}
/** The generic card of a measure: its score with numerator, denominator and interval, and its strata. */
| { kind: 'measure-card'; measure: string }
/** The histopathological confirmation: one card, two perspectives (a colposcopy and a biopsy
* PPV), the biopsy requests as one more reading of the biopsy one, and the original measure */
| {
kind: 'confirmation';
title: string;
colposcopy: { measure: string; modes: PpvMode[] };
biopsy: { measure: string; modes: PpvMode[]; requests: string };
}
| { kind: 'figures'; title?: string; figures: FigureSpec[] }
| {
@@ -115,9 +125,27 @@ export interface Catalog {
faded?: string[];
}
import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results';
import { Reading } from './measures';
import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, PpvMode } from './ppv';
import { VPH_MODES, vphSummary } from './vph';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
/** HPV categories the page leaves out (their reports stay in the total and the percentages). */
const HPV_HIDDEN = ['positive_incomplete', 'inconsistent'];
/** The cytology results by scenario, in the page's cytology colours. */
const CYTOLOGY_SCENARIO: Catalog = {
groups: [],
categories: CYTOLOGY_REPORTS.map(([code, label, color]) => ({ code, label, color, group: '' })),
};
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
@@ -136,22 +164,17 @@ const BIRADS: Catalog = {
{ code: '6', label: 'BI-RADS 6', color: '#7A3496', group: '' },
],
};
/** A breast biopsy's grades, and what stands in their place when there is none. */
const BIOPSY_GRADES = [
{ code: 'benign', label: 'Benigno', color: '#A8C243' },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2' },
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2' },
];
/** What «Sin biopsia» says, whatever the contract's category is called. */
const NO_BIOPSY_MEANS =
'«Sin biopsia»: no existe una biopsia vinculada según los datos disponibles.';
const INSTITUTIONAL = '#A8C243';
const NEUTRAL = '#C9CDD2';
const NO_RESULT = [
{ code: 'no_biopsy', label: 'Sin biopsia', color: '#C9CDD2' },
{ code: 'no_data', label: 'Sin dato', color: '#8C949C' },
];
const BREAST_BIOPSY: Catalog = {
groups: [
{ id: 'benign', label: 'No maligno', color: '#42C29C' },
{ id: 'malignant', label: 'Maligno', color: ROSE },
],
categories: [
{ code: 'benign', label: 'Benigno', color: OLIVE, group: 'benign' },
{ code: 'in_situ', label: 'Carcinoma in situ', color: '#9C42C2', group: 'malignant' },
{ code: 'invasive', label: 'Carcinoma invasor', color: '#5C42C2', group: 'malignant' },
],
};
export const PAGES: Record<string, Page> = {
tea: {
@@ -257,9 +280,9 @@ export const PAGES: Record<string, Page> = {
},
{
measure: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
title: 'Tasa de detección histopatológica',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} biopsias con grado conocido presentan carcinoma (in situ o invasor).',
note: '{num} de {den} biopsias con riesgo a carcinoma.',
},
{
measure: 'CAMA_EU38A',
@@ -279,27 +302,21 @@ export const PAGES: Record<string, Page> = {
],
opportunity: [
{
kind: 'route',
kind: 'boxes',
title: 'Tiempo de tamizaje a diagnóstico',
// from the mammography: only the two measures that start at it
sample: [
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
subtitles: true,
cards: [
{
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
measure: 'CAMA_EU38A',
title: 'Tiempo de toma de mastografía a interpretación radiológica',
},
],
step: [
{ label: 'Toma de mastografía a interpretación radiológica', measure: 'CAMA_EU38A' },
{
label: 'Interpretación radiológica a diagnóstico',
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
title: 'Tiempo de interpretación radiológica a diagnóstico',
},
{
label: 'Interpretación radiológica a resultado de biopsia',
measure: 'CAMA_DIAS_RESULTADO_BIOPSIA',
},
{ label: 'Diagnóstico a tratamiento' },
{ title: 'Tiempo de interpretación radiológica a resultado de biopsia' },
{ title: 'Tiempo de diagnóstico a tratamiento' },
{ measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO', title: 'Tiempo de tamizaje a diagnóstico' },
],
},
],
@@ -324,82 +341,162 @@ export const PAGES: Record<string, Page> = {
],
},
{
kind: 'readings',
kind: 'figures',
title: 'Resultado histopatológico por categoría BI-RADS',
note: 'Pacientes: su mastografía BI-RADS 4, 5 o 6 más grave y su biopsia más grave reportada, por fecha del examen. El porcentaje maligno se calcula solo sobre las pacientes con biopsia con grado.',
modes: [
figures: [
{
kind: 'outcomes',
label: 'Por categoría BI-RADS',
heading: 'Resultados por paciente',
caption: NO_BIOPSY_MEANS,
kind: 'rates',
title: 'Por categoría BI-RADS, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
stratum: 'birads',
rows: BIRADS.categories,
results: [...BIOPSY_GRADES, ...NO_RESULT],
malignant: ['in_situ', 'invasive'],
colored: true,
positive: ['in_situ', 'invasive'],
axis: 'Porcentaje con resultado maligno',
},
{
kind: 'counts',
label: 'Todas las categorías',
heading: 'Resultados por paciente',
caption: `Todas las categorías BI-RADS juntas. ${NO_BIOPSY_MEANS}`,
kind: 'donut',
title: 'Resultado de la biopsia, {p}',
measure: 'CAMA_HISTOPATOLOGIA_BIRADS',
catalog: [...BIOPSY_GRADES, ...NO_RESULT],
percent: true,
catalog: BREAST_BIOPSY,
center: 'con resultado',
},
],
},
{
kind: 'choice',
title: 'Confirmación histopatológica',
card: true,
choices: [
kind: 'card',
measure: 'CAMA_CONFIRMACION_BIRADS45',
title: 'Tasa de confirmación histopatológica',
value: '{pct} %',
note: '{num} de {den} mastografías BI-RADS 4 y 5 con reporte de biopsia.',
},
],
},
cacu: {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'route',
title: 'Tiempos de la ruta del tamizaje',
modes: { icd: 'CACU_TIEMPO_DIAGNOSTICO_CIE10' },
steps: [
{
label: 'Resultado de biopsias',
section: {
kind: 'readings',
title: 'Resultado de biopsias',
headline: 'CAMA_TASA_DETECCION_HISTOPATOLOGICA',
unit: 'biopsias',
note: 'Biopsias con resultado reportado, por fecha del reporte (no son pacientes ni mastografías). La tasa divide los carcinomas (in situ o invasor) entre biopsias con grado conocido. Los porcentajes de la distribución incluyen todas las biopsias reportadas, también «Sin dato» (sin grado), por lo que sus denominadores pueden ser distintos.',
modes: [
{
kind: 'counts',
label: 'Biopsias reportadas',
heading: 'Biopsias reportadas',
measure: 'CAMA_BIOPSIAS',
catalog: [...BIOPSY_GRADES, NO_RESULT[1]],
percent: true,
},
],
},
label: 'Resultado de citología',
measure: 'CACU_EU_TIEMPO_REPORTE',
step: 'Toma a resultado de citología',
stepMeasure: 'CACU_EU_TIEMPO_REPORTE',
},
{
label: 'Mastografías con biopsia',
section: {
kind: 'readings',
title: 'Mastografías con biopsia',
headline: 'CAMA_CONFIRMACION_BIRADS45',
unit: 'mastografías',
note: 'Mastografías BI-RADS 4, 4A, 4B, 4C o 5 con reporte, por fecha del examen: cuántas tienen un reporte de biopsia. Mide el seguimiento, no el resultado de la biopsia; no es equivalente a la tasa de detección.',
modes: [
{
kind: 'split',
label: 'Con y sin biopsia',
measure: 'CAMA_CONFIRMACION_BIRADS45',
yes: 'Con reporte de biopsia',
no: 'Sin reporte de biopsia',
colors: [INSTITUTIONAL, NEUTRAL],
},
],
},
label: 'Resultado de colposcopía',
measure: 'CACU_DIAS_TOMA_COLPOSCOPIA',
step: 'Del resultado de citología a la colposcopía',
stepMeasure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA',
},
{
label: 'Resultado de biopsia',
measure: 'CACU_DIAS_TOMA_BIOPSIA',
step: 'De la colposcopía al resultado de biopsia',
stepMeasure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
},
{
label: 'Diagnóstico',
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
step: 'Del resultado de biopsia al diagnóstico',
stepMeasure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
},
],
},
],
clinical: [
{
kind: 'results',
title: 'Resultados de citología, VPH y biopsia',
cytology: {
title: 'Distribución de resultados citológicos',
measure: 'CACU_EU7',
unit: 'pacientes',
catalog: CYTOLOGY_REPORTS,
notes: [
'Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.',
],
},
hpv: {
title: 'Resultados de VPH por genotipo',
measure: 'CACU_VPH_GENOTIPO',
unit: 'reportes',
catalog: HPV_REPORTS,
hide: HPV_HIDDEN,
notes: [
'Un reporte de VPH por paciente y fecha de toma; el periodo es el de la toma. Cuenta reportes, ' +
'no pacientes: es una medida distinta de las pacientes evaluadas por resultado de VPH.',
'Los valores nulos no se cuentan como negativos.',
],
},
biopsy: {
title: 'Resultados de biopsia cervical',
measure: 'CACU_BIOPSIA_RESULTADOS',
unit: 'reportes',
catalog: BIOPSY_REPORTS,
groups: [
{ before: 'normal', label: 'Menor que LIEAG', codes: ['normal', 'LSIL'] },
{ before: 'HSIL', label: 'LIEAG o más', codes: ['HSIL', 'CIS', 'carcinoma'] },
],
notes: [
'Reportes de biopsia con histología clasificable; el periodo es el de la fecha del reporte. ' +
'Las órdenes sin reporte no están incluidas.',
],
},
complement: [
{
kind: 'scenario-bars',
title: 'Resultados citológicos por escenario clínico, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY_SCENARIO,
stratum: 'follow_up_status',
},
],
},
{ kind: 'ppv', measure: 'CACU_VPH', modes: VPH_MODES, summary: vphSummary },
{
kind: 'confirmation',
title: 'Tasa de confirmación histopatológica',
colposcopy: { measure: 'CACU_VPP_COLPOSCOPIA', modes: PPV_COLPOSCOPY_MODES },
biopsy: {
measure: 'CACU_VPP_BIOPSIA',
modes: PPV_BIOPSY_MODES,
requests: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
},
},
],
},
cacu: CACU,
};
/** One panel of Trazabilidad (tests/fixtures/reference/<domain>/ui, tab "Trazabilidad"): a
+160
View File
@@ -0,0 +1,160 @@
<ng-template #heading let-text>
@if (embedded()) {
<h3 class="ppv-title">{{ text }}</h3>
} @else {
<h2 class="figure-card-title">{{ text }}</h2>
}
</ng-template>
<ng-template #bars let-rows="rows" let-label="label" let-percent="percent">
@let withInterval = hasInterval(rows);
<div class="ppv-rows" role="table" [attr.aria-label]="label">
<div class="ppv-row ppv-head" role="row" [class.with-interval]="withInterval">
<span role="columnheader">Grupo</span>
<span role="columnheader" class="ppv-axis">
<span>0 %</span><span>50 %</span><span>100 %</span>
</span>
<span role="columnheader" class="num">n/N</span>
<span role="columnheader" class="num">{{ percent ?? '%' }}</span>
@if (withInterval) {
<span role="columnheader" class="num">IC 95 %</span>
}
</div>
@for (row of rows; track row.code) {
<div class="ppv-row" role="row" [class.with-interval]="withInterval">
<span role="rowheader" class="ppv-label">{{ row.label }}</span>
<span class="ppv-track" aria-hidden="true">
<span
class="ppv-bar"
[style.width.%]="row.percent ?? 0"
[style.background]="row.color"
></span>
</span>
<span role="cell" class="num">{{ row.numerator }}/{{ row.denominator }}</span>
<span role="cell" class="num">
{{ row.percent === undefined ? '—' : fixed(row.percent) + ' %' }}
</span>
@if (withInterval) {
<span role="cell" class="num">
{{
row.low === undefined || row.high === undefined
? '—'
: fixed(row.low) + '–' + fixed(row.high) + ' %'
}}
</span>
}
</div>
}
</div>
@if (!withInterval) {
<p class="state ppv-caption">El servidor no publica el intervalo por grupo.</p>
}
</ng-template>
<ng-template #toggles>
<mat-button-toggle-group
class="ppv-modes"
aria-label="Lectura de la medida"
[value]="selected()"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.id) {
<mat-button-toggle [value]="m.id">{{ m.label }}</mat-button-toggle>
}
@if (alternate(); as a) {
<mat-button-toggle value="alternate">{{ a.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
</ng-template>
<ng-template #content>
@if (loading()) {
<ng-container *ngTemplateOutlet="heading; context: { $implicit: title() }" />
<app-loading what="la medida" [figure]="true" />
} @else if (alternate(); as a) {
@if (selected() === 'alternate') {
<ng-container *ngTemplateOutlet="heading; context: { $implicit: a.title }" />
<p class="measure-score">{{ a.score }}{{ a.detail ? ' · ' + a.detail : '' }}</p>
@if (a.note) {
<p class="state">{{ a.note }}</p>
}
<ng-container *ngTemplateOutlet="toggles" />
@if (a.message) {
<p class="state" [attr.role]="a.alert ? 'alert' : null">{{ a.message }}</p>
} @else {
<p class="state ppv-caption">{{ a.caption }}</p>
<ng-container
*ngTemplateOutlet="
bars;
context: { rows: a.rows, label: a.label, percent: a.percentLabel }
"
/>
@for (line of a.lines; track line) {
<p class="state ppv-caption">{{ line }}</p>
}
}
} @else {
<ng-container *ngTemplateOutlet="measureView" />
}
} @else {
<ng-container *ngTemplateOutlet="measureView" />
}
</ng-template>
<ng-template #measureView>
<ng-container *ngTemplateOutlet="heading; context: { $implicit: title() }" />
@if (!published()) {
<p class="state">Medida no publicada por el servidor.</p>
@if (alternate()) {
<ng-container *ngTemplateOutlet="toggles" />
}
} @else if (reading()?.error) {
<p class="state" role="alert">No se pudo consultar esta medida.</p>
@if (alternate()) {
<ng-container *ngTemplateOutlet="toggles" />
}
} @else {
<p class="measure-score">{{ score() }} · {{ detail() }}</p>
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (empty() && !alternate()) {
<p class="state">Sin pacientes en el periodo.</p>
} @else {
<ng-container *ngTemplateOutlet="toggles" />
@if (empty()) {
<p class="state">Sin pacientes en el periodo.</p>
} @else {
<p class="state ppv-caption">{{ mode().caption }}</p>
@if (!mode().stratum && !mode().rows) {
@if (donut(); as figure) {
<app-plot [figure]="figure" [height]="260" />
} @else {
<p class="state">El reporte no trae numerador y denominador consistentes.</p>
}
} @else if (rows().length) {
<ng-container
*ngTemplateOutlet="
bars;
context: { rows: rows(), label: mode().label, percent: mode().percentLabel }
"
/>
} @else {
<p class="state">Sin pacientes en esta lectura en el periodo.</p>
}
}
}
}
</ng-template>
@if (embedded()) {
<div class="ppv-embedded">
<ng-container *ngTemplateOutlet="content" />
</div>
} @else {
<mat-card appearance="outlined" class="figure-card measure-card ppv-card">
<mat-card-content>
<ng-container *ngTemplateOutlet="content" />
</mat-card-content>
</mat-card>
}
+91
View File
@@ -0,0 +1,91 @@
:host {
display: block;
}
.figure-card {
margin-top: 24px;
}
h2.figure-card-title {
font-size: 18px;
font-weight: 500;
margin: 0 0 12px;
}
.measure-score {
font-weight: 500;
margin: var(--space-2) 0;
}
.state {
color: var(--color-text-secondary);
font-size: 14px;
}
.ppv-modes {
flex-wrap: wrap;
margin: var(--space-3) 0 var(--space-2);
max-width: 100%;
}
.ppv-caption {
font-size: 13px;
margin: var(--space-2) 0;
}
.ppv-rows {
font-size: 13px;
margin-top: var(--space-2);
}
.ppv-row {
align-items: center;
display: grid;
gap: 12px;
grid-template-columns: minmax(150px, 26%) minmax(120px, 1fr) 64px 64px;
padding: 4px 0;
}
.ppv-row.with-interval {
grid-template-columns: minmax(150px, 26%) minmax(120px, 1fr) 64px 64px 110px;
}
.ppv-head {
color: var(--color-text-secondary);
font-weight: 500;
}
.ppv-axis {
display: flex;
font-weight: 400;
justify-content: space-between;
}
.ppv-label {
font-weight: 500;
min-width: 0;
}
.ppv-track {
background: #eef1f3;
background-image: linear-gradient(to right, #d8dde1 1px, transparent 1px);
background-position: 50% 0;
background-repeat: no-repeat;
display: block;
height: 16px;
}
.ppv-bar {
display: block;
height: 100%;
}
.num {
font-variant-numeric: tabular-nums;
text-align: right;
white-space: nowrap;
}
@media (max-width: 700px) {
.ppv-row,
.ppv-row.with-interval {
grid-template-columns: 1fr 56px 56px;
}
.ppv-track,
.ppv-axis {
grid-column: 1 / -1;
order: 5;
}
}
.ppv-embedded {
display: block;
}
h3.ppv-title {
font-size: 16px;
font-weight: 500;
margin: 0 0 12px;
}
+65
View File
@@ -0,0 +1,65 @@
import { NgTemplateOutlet } from '@angular/common';
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading';
import { Plot } from '../plot';
import { Reading } from './measures';
import { ppvDonut, PpvAlternate, PpvMode, PpvRow, ppvRows } from './ppv';
/** A positive predictive value in one reading at a time: its score, numerator, denominator and
* interval and what it is and is not stay in view; the buttons choose the whole (a donut) or one
* stratifier of the report (compact bars on a common 0 to 100 % scale, n/N and percent). Every
* measure of this kind can use it by giving its modes. An `alternate` is one more button whose
* view comes from another measure and replaces the whole of the card's own (title, score, note
* and bars), so what is shown always belongs to the measure chosen. */
@Component({
selector: 'app-ppv-card',
imports: [Loading, MatButtonToggleModule, MatCardModule, NgTemplateOutlet, Plot],
templateUrl: './ppv-card.html',
styleUrl: './ppv-card.scss',
})
export class PpvCard {
readonly title = input.required<string>();
/** what the PPV is and is not (never hidden) */
readonly note = input<string>();
/** the score line: "20.0 %" and "3 de 15 pacientes. IC 95 %: …" */
readonly score = input.required<string>();
readonly detail = input.required<string>();
readonly reading = input<Reading>();
readonly loading = input(false);
readonly published = input(true);
readonly modes = input.required<PpvMode[]>();
/** the donut's name for those who confirm */
readonly confirmed = input('Con histología LIEBG o mayor');
/** inside another card: no card of its own, and a smaller title */
readonly embedded = input(false);
/** one more reading, from another measure */
readonly alternate = input<PpvAlternate>();
protected readonly chosen = signal<string | undefined>(undefined);
protected readonly selected = computed(() =>
this.chosen() === 'alternate' && this.alternate() ? 'alternate' : this.mode().id,
);
protected readonly mode = computed(
() => this.modes().find((m) => m.id === this.chosen()) ?? this.modes()[0],
);
protected readonly donut = computed(() => {
const figure = this.mode().figure;
return figure ? figure(this.reading()) : ppvDonut(this.reading(), this.confirmed());
});
protected readonly rows = computed(() => {
const { rows, stratum } = this.mode();
if (rows) return rows(this.reading());
return stratum ? ppvRows(this.reading(), stratum) : [];
});
protected hasInterval(rows: PpvRow[]): boolean {
return rows.some((r) => r.low !== undefined);
}
/** No patients: a PPV's denominator, or a cohort's population. */
protected readonly empty = computed(() => {
const p = this.reading()?.populations ?? {};
return !(p['denominator'] ?? p['initial-population'] ?? 0);
});
protected readonly fixed = (n: number) => n.toFixed(1);
}
+92
View File
@@ -0,0 +1,92 @@
import { describe, expect, it } from 'vitest';
import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, ppvDonut, ppvRows } from './ppv';
import { Reading } from './measures';
const cell = (numerator: number, denominator: number) => ({
'initial-population': denominator,
numerator,
denominator,
});
const report = (strata: Reading['strata'], numerator = 3, denominator = 15): Reading => ({
populations: { 'initial-population': denominator, numerator, denominator },
score: numerator / denominator,
strata,
});
describe('PPV by group', () => {
it('lists the groups in the page order with n/N and percent, and neutral for no data', () => {
const rows = ppvRows(
report({
referral_cytology: {
no_data: cell(1, 4),
'HSIL+': cell(2, 2),
'ASCUS+': cell(2, 8),
},
}),
'referral_cytology',
);
expect(rows.map((r) => r.code)).toEqual(['ASCUS+', 'HSIL+', 'no_data']);
expect(rows[0]).toMatchObject({ numerator: 2, denominator: 8, percent: 25 });
expect(rows[1].percent).toBe(100);
expect(rows[2].color).toBe('#C9CDD2');
// the colours are the cytology ones of the rest of the page
expect(rows[0].color).toBe('#2778B8');
expect(rows[1].color).toBe('#CE4778');
});
it('keeps a group without patients as no rate (not 0 %) and never invents an absent group', () => {
const rows = ppvRows(
report({ histology_level: { 'LIEBG+': cell(0, 0), 'LIEAG+': cell(0, 4) } }),
'histology_level',
);
expect(rows.map((r) => r.code)).toEqual(['LIEBG+', 'LIEAG+']);
expect(rows[0].percent).toBeUndefined();
expect(rows[1].percent).toBe(0);
expect(ppvRows(report({}), 'screening_round')).toEqual([]);
expect(ppvRows(undefined, 'screening_round')).toEqual([]);
});
it('leaves out a cell that does not add up instead of correcting it', () => {
const rows = ppvRows(
report({ screening_round: { initial: cell(5, 4), subsequent: cell(1, 2) } }),
'screening_round',
);
expect(rows.map((r) => r.code)).toEqual(['subsequent']);
});
it('shows an interval only when the report publishes it for the group', () => {
const r = report({ referral_hpv: { negative: cell(1, 5), positive: cell(2, 4) } });
r.stratumScores = { referral_hpv: { positive: { median: 0.5, low: 0.15, high: 0.85 } } };
const rows = ppvRows(r, 'referral_hpv');
expect(rows[0].low).toBeUndefined();
expect(rows[1].low).toBeCloseTo(15);
expect(rows[1].high).toBeCloseTo(85);
});
it('draws the whole as a donut of those who confirm and the rest, and nothing when it is not whole', () => {
const fig = ppvDonut(report({}), 'Con histología LIEBG o mayor')!;
expect((fig.data[0] as { values: number[] }).values).toEqual([3, 12]);
expect(ppvDonut(report({}, 3, 0), 'x')).toBeUndefined();
expect(ppvDonut(undefined, 'x')).toBeUndefined();
});
it('declares the five readings of the colposcopy PPV, total first, and says which overlap', () => {
expect(PPV_COLPOSCOPY_MODES.map((m) => m.stratum)).toEqual([
undefined,
'referral_cytology',
'referral_hpv',
'histology_level',
'screening_round',
]);
for (const id of ['cytology', 'hpv', 'histology'])
expect(PPV_COLPOSCOPY_MODES.find((m) => m.id === id)!.caption).toMatch(
/traslapan|excluyentes/,
);
});
it('gives the biopsy PPV the same readings with its own denominator', () => {
expect(PPV_BIOPSY_MODES.map((m) => m.id)).toEqual(PPV_COLPOSCOPY_MODES.map((m) => m.id));
expect(PPV_BIOPSY_MODES[0].caption).toContain('con biopsia reportada');
expect(PPV_COLPOSCOPY_MODES[0].caption).toContain('con colposcopía registrada');
expect(PPV_BIOPSY_MODES[1].caption).toBe(PPV_COLPOSCOPY_MODES[1].caption);
});
});
+198
View File
@@ -0,0 +1,198 @@
import type { Figure } from '../plot';
import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results';
import { name, Reading } from './measures';
/** One way to read a positive predictive value: the whole, or a stratifier of the report. */
export interface PpvMode {
id: string;
label: string;
/** the report's stratifier (none: the whole, shown as a donut) */
stratum?: string;
/** what the groups are, and whether they overlap, said under the bars */
caption: string;
/** the bars when they do not come from a stratifier of the report as a PPV's do */
rows?: (reading: Reading | undefined) => PpvRow[];
/** the whole's figure when it is not the PPV donut */
figure?: (reading: Reading | undefined) => Figure | undefined;
/** the header of the percent column (default "%") */
percentLabel?: string;
}
/** One bar: the patients that confirm (or are positive) over the patients of the group, as the
* report counts them. */
export interface PpvRow {
code: string;
label: string;
color: string;
numerator: number;
denominator: number;
/** none when the group has no patients (a zero rate is not the same) */
percent?: number;
/** the interval, only when the report publishes it for the group (percent) */
low?: number;
high?: number;
}
const NEUTRAL = '#C9CDD2';
const NEUTRAL_DARK = '#9AA3AB';
/** The colour a category has elsewhere on the page (cytology, HPV, histology), by its code there. */
const of = (rows: readonly (readonly [string, string, string])[], code: string) =>
rows.find((r) => r[0] === code)![2];
/** Colours and order of each stratifier's groups: the page's own for cytology, HPV and
* histology; steel tones for the screening round; neutral for "no data". Colours name a
* category, they are not thresholds. */
const GROUPS: Record<string, [code: string, color: string][]> = {
referral_cytology: [
['ASCUS+', of(CYTOLOGY_REPORTS, 'ASC-US')],
['LSIL+', of(CYTOLOGY_REPORTS, 'LSIL')],
['HSIL+', of(CYTOLOGY_REPORTS, 'HSIL')],
['no_data', NEUTRAL],
],
referral_hpv: [
['negative', of(HPV_REPORTS, 'negative')],
['positive', of(HPV_REPORTS, 'positive_other')],
['hpv_16', of(HPV_REPORTS, 'positive_16')],
['hpv_18', of(HPV_REPORTS, 'positive_18')],
['no_data', NEUTRAL],
],
histology_level: [
['LIEBG+', of(BIOPSY_REPORTS, 'LSIL')],
['LIEAG+', of(BIOPSY_REPORTS, 'HSIL')],
['invasive', of(BIOPSY_REPORTS, 'carcinoma')],
],
screening_round: [
['initial', '#5F7F9A'],
['subsequent', '#8FA7BB'],
['no_data', NEUTRAL],
],
};
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
/** A stratifier's groups as bars, in the page's order. A group the report does not list is not
* drawn (it is not a zero); a cell that is not whole counts, or whose numerator exceeds its
* denominator, is left out rather than corrected. */
export function ppvRows(reading: Reading | undefined, stratum: string): PpvRow[] {
const cells = reading?.strata[stratum];
if (!cells) return [];
const order = GROUPS[stratum] ?? [];
const known = order.map(([code]) => code);
const codes = [
...known.filter((c) => c in cells),
...Object.keys(cells).filter((c) => !known.includes(c)),
];
return codes.flatMap((code) => {
const { numerator, denominator } = cells[code];
if (!whole(numerator) || !whole(denominator) || numerator > denominator) return [];
const score = reading?.stratumScores?.[stratum]?.[code];
return [
{
code,
label: name(code),
color: order.find(([c]) => c === code)?.[1] ?? NEUTRAL_DARK,
numerator,
denominator,
percent: denominator ? (100 * numerator) / denominator : undefined,
...(score?.low !== undefined && score.high !== undefined
? { low: 100 * score.low, high: 100 * score.high }
: {}),
},
];
});
}
/** The whole PPV as a donut: those who confirm, and the rest in a neutral tone. */
export function ppvDonut(reading: Reading | undefined, confirmed: string): Figure | undefined {
const { numerator, denominator } = reading?.populations ?? {};
if (!whole(numerator) || !whole(denominator) || !denominator || numerator > denominator)
return undefined;
return {
data: [
{
type: 'pie',
hole: 0.62,
labels: [confirmed, 'Resto'],
values: [numerator, denominator - numerator],
sort: false,
direction: 'clockwise',
textinfo: 'value+percent',
textposition: 'outside',
marker: { colors: ['#6A8000', NEUTRAL] },
},
],
layout: {
height: 260,
showlegend: true,
margin: { t: 16, r: 8, b: 16, l: 8 },
legend: { orientation: 'h' },
},
};
}
/** The readings of a referral PPV (the colposcopy's and the biopsy's publish the same four
* stratifiers). The groups of cytology and histology are cumulative and overlap; the HPV ones
* overlap too (a genotype is also a positive); the rounds do not. `patients` says whose the
* denominator is. */
const ppvModes = (patients: string): PpvMode[] => [
{
id: 'total',
label: 'Total',
caption: `Pacientes con histología LIEBG o mayor sobre las pacientes ${patients} en el periodo.`,
},
{
id: 'cytology',
label: 'Citología previa',
stratum: 'referral_cytology',
caption:
'Por citología previa asociada por fechas: es una asociación por fechas, no un vínculo clínico. ' +
'Cada grupo incluye su categoría y las más severas, así que los grupos se traslapan y no son excluyentes. ' +
'«Sin dato»: sin citología previa asociada en los 365 días anteriores.',
},
{
id: 'hpv',
label: 'VPH previo',
stratum: 'referral_hpv',
caption:
'Por VPH de la citología previa asociada por fechas (asociación por fechas, no vínculo clínico). ' +
'Los grupos se traslapan: «Positivo» incluye a quienes son positivas para VPH 16 o 18, y una paciente puede estar en ambos genotipos. ' +
'«Sin dato»: sin resultado de VPH o sin citología previa asociada.',
},
{
id: 'histology',
label: 'Nivel de histología',
stratum: 'histology_level',
caption:
'Por nivel de histología confirmado. ' +
'Tres numeradores distintos sobre el mismo denominador (no son categorías excluyentes): cada nivel incluye los más severos.',
},
{
id: 'round',
label: 'Ronda de tamizaje',
stratum: 'screening_round',
caption:
'Por tamizaje inicial o subsecuente. ' +
'Cada paciente está en un solo grupo. «Sin dato»: sin clasificación de tamizaje inicial o subsecuente.',
},
];
export const PPV_COLPOSCOPY_MODES = ppvModes('con colposcopía registrada');
export const PPV_BIOPSY_MODES = ppvModes('con biopsia reportada');
/** One more reading of a PPV card that comes from another measure (the biopsy requests): it
* brings its own title, heading figures, note and bars, and replaces the card's own while chosen. */
export interface PpvAlternate {
label: string;
title: string;
score: string;
detail: string;
note?: string;
caption: string;
rows: PpvRow[];
/** secondary counts, one per line */
lines: string[];
/** instead of the bars: why there are none (not published, failed, no records) */
message?: string;
alert?: boolean;
percentLabel?: string;
}
-381
View File
@@ -1,381 +0,0 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { bars, grouped, hiddenNote, Mode, unavailable } from './bars';
import { Reading } from './measures';
/** A card read one mode at a time: its title, its headline, the toggle and the bars. */
@Component({
selector: 'app-readings',
host: { '[class.cama]': 'camaStyle()' },
imports: [Loading, MatButtonToggleModule, Plot],
template: `
@if (!hideTitle()) {
<h3 class="title">{{ title() }}</h3>
}
@if (headline()) {
<p class="headline">{{ headline() }}</p>
}
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1 && !view()) {
<mat-button-toggle-group
[attr.aria-label]="title()"
[value]="mode().label"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.label) {
<mat-button-toggle [value]="m.label">{{ m.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
@if (mode().heading) {
<h4 class="heading">{{ mode().heading }}</h4>
}
@if (mode().caption) {
<p class="state">{{ mode().caption }}</p>
}
@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]="height()" />
@if (hidden(); as why) {
<p class="state">{{ why }}</p>
}
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
<tr>
<th></th>
@for (h of t.head; track h) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<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 {
<span class="track" [class.parts]="!!row.segments" aria-hidden="true">
@if (row.segments; as parts) {
@for (p of parts; track $index) {
<span
class="bar"
[style.width.%]="p.width"
[style.background]="p.color"
[attr.title]="p.title"
></span>
}
} @else {
<span
class="bar"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
}
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m" [style.background]="t.markColor"></span>
}
</span>
}
</th>
@for (c of row.cells; track $index) {
<td>{{ c }}</td>
}
</tr>
}
</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) {
<span><i [style.background]="l.color"></i>{{ l.label }}</span>
}
</p>
}
} @else {
<p class="state">Sin datos en el periodo.</p>
}
`,
styles: `
:host {
display: block;
min-width: 0;
}
:host(.cama) {
overflow-x: auto;
}
.title {
margin: 0 0 8px;
}
:host(.cama) .title {
font-size: 18px;
font-weight: 500;
}
.heading {
font-size: 14px;
font-weight: 500;
margin: 12px 0 4px;
}
.headline {
font-weight: 500;
}
:host(.cama) .headline {
margin: 8px 0;
}
:host(.cama) .state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
mat-button-toggle-group {
flex-wrap: wrap;
margin: 4px 0;
}
table {
border-collapse: collapse;
width: 100%;
}
:host(.cama) table {
font-size: 13px;
}
:host(.cama) thead th {
font-weight: 500;
}
th,
td {
font-weight: 400;
padding: 4px 6px;
text-align: right;
white-space: nowrap;
}
th[scope='row'] {
text-align: left;
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;
height: 8px;
position: relative;
}
.bar {
background: #a8c243;
display: block;
height: 100%;
}
.parts {
display: flex;
}
.none {
color: rgba(0, 0, 0, 0.6);
display: block;
font-size: 12px;
font-weight: 400;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 16px;
margin: 8px 0 0;
}
.legend i {
display: inline-block;
height: 10px;
margin-right: 6px;
width: 10px;
}
.mark {
background: #333;
height: 12px;
position: absolute;
top: -2px;
width: 2px;
}
`,
})
export class Readings {
readonly title = input.required<string>();
readonly headline = input('');
readonly note = input('');
/** the card around it names it already (tabs inside one card) */
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>();
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal('');
protected readonly mode = computed(
() => 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,
);
}
-183
View File
@@ -1,183 +0,0 @@
import { Component, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { Loading } from '../loading';
import { DurationRow, durationMax } from './durations';
/** A screening route as one compact card: a bar per step with its median, its observations
* and its quartiles, read step by step or cumulatively from the sample. A step that is not
* published, or has no measurements in the period, keeps its row and says so. */
@Component({
selector: 'app-route-card',
imports: [Loading, MatButtonToggleModule, MatCardModule],
template: `
<mat-card appearance="outlined">
<mat-card-content>
<div class="head">
<h3>{{ title() }}</h3>
@if (sample().length && step().length) {
<mat-button-toggle-group
aria-label="Lectura de los tiempos"
[value]="mode()"
(change)="mode.set($event.value)"
>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (loading()) {
<app-loading what="los tiempos" [figure]="true" />
} @else {
@let rows = mode() === 'sample' ? sample() : step();
@let max = scale(rows);
<p class="state">
@if (mode() === 'sample') {
Mediana de días desde la toma de la mastografía hasta cada etapa; cada medida se
calcula por separado.
} @else {
Cada barra es la mediana de su paso, desde cero y por separado; los pasos pueden
corresponder a poblaciones diferentes, por lo que las medianas no se suman.
}
Las marcas indican el primer y tercer cuartil.
@if (max) {
Escala: 0 a {{ max }} días.
}
</p>
<table [attr.aria-label]="title()">
<thead>
<tr>
<th>{{ mode() === 'sample' ? 'Etapa' : 'Paso' }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr [attr.data-status]="row.status">
<th scope="row">
{{ row.label }}
@if (row.status === 'value') {
<span class="track" aria-hidden="true">
<span
class="bar"
[style.width.%]="max ? (100 * row.median!) / max : 0"
></span>
@if (row.low !== undefined && row.high !== undefined) {
<span
class="mark"
[style.left.%]="max ? (100 * row.low) / max : 0"
></span>
<span
class="mark"
[style.left.%]="max ? (100 * row.high) / max : 0"
></span>
}
</span>
} @else {
<span class="none">
{{
row.status === 'empty'
? 'Sin mediciones en el periodo'
: 'Indicador no publicado'
}}
</span>
}
</th>
<td>{{ row.status === 'value' ? row.median + ' días' : '—' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{
row.low === undefined || row.high === undefined
? '—'
: row.low + '–' + row.high
}}
</td>
</tr>
}
</tbody>
</table>
}
</mat-card-content>
</mat-card>
`,
styles: `
:host {
display: block;
margin-top: 24px;
}
.head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
h3 {
font-size: 18px;
font-weight: 500;
margin: 0;
}
.state {
color: var(--color-text-secondary);
font-size: 13px;
margin: 8px 0;
}
table {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
th {
font-weight: 500;
text-align: left;
}
th[scope='row'] {
padding: 5px 0;
}
td,
thead th:not(:first-child) {
font-variant-numeric: tabular-nums;
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
position: relative;
}
.bar {
background: #42a77e;
display: block;
height: 100%;
}
.mark {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.none {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
`,
})
export class RouteCard {
readonly title = input.required<string>();
/** The rows from the sample, and the rows step by step. */
readonly sample = input.required<DurationRow[]>();
readonly step = input.required<DurationRow[]>();
readonly loading = input(false);
protected readonly mode = signal<'sample' | 'step'>('step');
protected readonly scale = durationMax;
}
-181
View File
@@ -1,181 +0,0 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure } from 'fhir/r4';
import { Mode } from './bars';
import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { ReadingsCard, Section } from './pages';
import { Readings } from './readings';
/** The applied period's readings and the measures they are of. */
export interface Source {
loading: boolean;
reading: (measure: string) => Reading | undefined;
measure: (name: string) => Measure | undefined;
}
type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
/** A card of readings, several side by side, or one of several at a time. */
@Component({
selector: 'app-section',
imports: [MatButtonToggleModule, MatCardModule, Readings],
template: `
@let s = section();
@if (s.kind === 'readings') {
<mat-card appearance="outlined">
<mat-card-content>
<app-readings
[title]="s.title"
[camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)"
[note]="s.note ?? ''"
[modes]="s.modes"
[view]="view()"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
</mat-card-content>
</mat-card>
} @else if (s.kind === 'choice' && s.card) {
@let open = chosen() || s.choices[0].label;
<mat-card appearance="outlined" class="choice-card">
<mat-card-content>
<h3 class="title">{{ s.title }}</h3>
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-readings
[title]="c.section.title"
[hideTitle]="true"
[camaStyle]="true"
[headline]="headlineOf(c.section)"
[note]="c.section.note ?? ''"
[modes]="c.section.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
}
}
</mat-card-content>
</mat-card>
} @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()"
[view]="inner.follows ? picked() || s.views?.[0] : undefined"
/>
}
</div>
} @else {
@let open = chosen() || s.choices[0].label;
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-section [section]="c.section" [of]="of()" />
}
}
}
}
`,
styles: `
:host {
display: block;
margin-top: 24px;
min-width: 0;
}
.views {
flex-wrap: wrap;
margin: 4px 0 8px;
}
.title {
font-size: 18px;
font-weight: 500;
margin: 0 0 8px;
}
.choice-card app-readings {
margin-top: 8px;
}
.columns {
display: grid;
column-gap: 16px;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 480px), 1fr));
}
.columns > :last-child:nth-child(odd) {
grid-column: 1 / -1;
}
`,
})
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 {
return s.modes.some((mode) => !!mode.heading);
}
/** A reading card's headline: its measure's score and its counts, in its own units. */
protected headlineOf(s: ReadingsCard): string {
const code = s.headline;
const measure = code && this.of().measure(code);
const r = code && this.of().reading(code);
if (!measure || !r) return '';
const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
}
protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined;
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, 'category', mode.colors);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(
r,
{ groups: [], categories },
mode.stratum ?? 'follow_up_status',
name,
mode.order,
{ fill: mode.complete, ofAll: mode.ofAll },
);
});
}
+406 -11
View File
@@ -83,20 +83,415 @@
</section>
}
<ng-template #routeTable let-rows let-title="title" let-first="first">
<table class="distribution route-table" [attr.aria-label]="title">
<thead>
<tr>
<th>{{ first }}</th>
<th>Mediana</th>
<th>Observaciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
@if (row.median !== undefined) {
<span class="bar-track duration-track" aria-hidden="true">
<span
class="bar"
[style.width.%]="routeMax(rows) ? (100 * row.median) / routeMax(rows) : 0"
></span>
@if (row.low !== undefined && row.high !== undefined) {
<span
class="quartile"
[style.left.%]="routeMax(rows) ? (100 * row.low) / routeMax(rows) : 0"
></span>
<span
class="quartile"
[style.left.%]="routeMax(rows) ? (100 * row.high) / routeMax(rows) : 0"
></span>
}
</span>
} @else {
<span class="no-data">Sin mediciones en el periodo</span>
}
</th>
<td>{{ row.median === undefined ? '—' : row.median + ' días' }}</td>
<td>{{ row.observations ?? '—' }}</td>
<td>
{{ row.low === undefined || row.high === undefined ? '—' : row.low + '–' + row.high }}
</td>
</tr>
}
</tbody>
</table>
</ng-template>
<ng-template #distBlock let-spec let-untitled="untitled">
@if (!untitled) {
<h3 class="dist-title">{{ spec.title }}</h3>
}
@for (note of spec.notes; track note) {
<p class="state">{{ note }}</p>
}
@if (reports.isLoading()) {
<app-loading what="la distribución" [figure]="true" />
} @else if (distOf(spec); as d) {
<p class="state">
{{ d.total }} {{ spec.unit }} en las categorías de la distribución
@if (d.outside) {
· {{ d.outside }} fuera de ellas
}
@if (d.noData) {
· {{ d.noData }} sin dato
}
· escala de las barras de 0 a {{ d.max }}.
</p>
@if (d.hiddenCount) {
<p class="state hidden-note">
Categorías que esta vista no desglosa (genotipificación incompleta, indeterminado o no
clasificable). Total en ellas: {{ d.hiddenCount }} ({{ spec.unit }}), incluido en el total
y en los porcentajes.
</p>
}
@if (!d.total) {
<p class="state">Sin {{ spec.unit }} en el periodo (cero registros, no falta de datos).</p>
}
<table class="distribution" [attr.aria-label]="spec.title">
<thead>
<tr>
<th>Categoría</th>
<th>{{ spec.unit }}</th>
<th>%</th>
</tr>
</thead>
<tbody>
@for (item of d.items; track $index) {
@if (item.kind === 'group') {
<tr class="group">
<th scope="rowgroup" colspan="3">{{ item.label }} · {{ item.count }}</th>
</tr>
} @else {
<tr>
<th scope="row">
<span class="distribution-label">{{ item.label }}</span>
<span class="bar-track" aria-hidden="true">
<span
class="bar"
[style.width.%]="d.max ? (100 * item.count) / d.max : 0"
[style.background]="item.color"
></span>
</span>
</th>
<td>{{ item.count }}</td>
<td>{{ d.total ? ((100 * item.count) / d.total).toFixed(1) + ' %' : '—' }}</td>
</tr>
}
}
</tbody>
</table>
} @else if (rd(spec.measure)?.error) {
<p class="state" role="alert">No se pudo consultar esta medida.</p>
} @else {
<p class="state">
Distribución no disponible para este periodo (la medida no está publicada o su reporte no es
consistente).
</p>
}
</ng-template>
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('readings')
@case ('columns')
@case ('choice') {
<app-section [section]="section" [of]="of()" />
}
@case ('route') {
<app-route-card
[title]="section.title"
[sample]="stepRows(section, 'sample')"
[step]="stepRows(section, 'step')"
[loading]="reports.isLoading()"
/>
<mat-card appearance="outlined" class="route-card">
<mat-card-content>
<div class="route-head">
<h3 class="route-title">{{ section.title }}</h3>
@if (section.modes) {
<mat-button-toggle-group
class="route-toggle"
aria-label="Lectura de la ruta del tamizaje"
[value]="routeMode()"
(change)="routeMode.set($event.value)"
>
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle>
<mat-button-toggle value="icd10">Desglose por CIE-10</mat-button-toggle>
</mat-button-toggle-group>
}
</div>
@if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" />
} @else if (!section.modes || routeMode() === 'sample') {
@let rows = stepRows(section, 'sample');
@if (rows.some((r) => r.median !== undefined)) {
<p class="state">
Mediana desde la toma de muestra hasta cada etapa. Escala: 0 a
{{ routeMax(rows) }} días. Las marcas indican el primer y tercer cuartil.
</p>
<ng-container
*ngTemplateOutlet="
routeTable;
context: {
$implicit: rows,
title: 'Tiempos de la ruta del tamizaje',
first: 'Etapa',
}
"
/>
} @else {
<p class="state">Sin tiempos publicados en el periodo.</p>
}
} @else if (routeMode() === 'step') {
@let rows = stepRows(section, 'step');
@if (rows.some((r) => r.median !== undefined)) {
<p class="state">
Cada barra es la mediana del tramo, desde cero y por separado; las marcas indican
el primer y tercer cuartil. Escala: 0 a {{ routeMax(rows) }} días. Los tramos
pueden corresponder a poblaciones diferentes, por lo que las medianas no se suman.
</p>
<ng-container
*ngTemplateOutlet="
routeTable;
context: {
$implicit: rows,
title: 'Tiempos por tramo de la ruta del tamizaje',
first: 'Tramo',
}
"
/>
} @else {
<p class="state">Sin tiempos por tramo publicados en el periodo.</p>
}
} @else {
@if (icdOf(section); as icd) {
<p class="state">
Desglose exploratorio basado en la asociación temporal existente entre la toma y
la nota de diagnóstico; no confirma un vínculo clínico.
</p>
@if (icd.reading?.error) {
<p class="state" role="alert">No se pudo consultar el desglose por CIE-10.</p>
} @else if (!icd.reading) {
<p class="state">Desglose no disponible en este servidor o periodo.</p>
} @else {
@let max = icdMax(icd.rows);
<p class="state">
{{ icd.reading.populations['measure-observation'] ?? 0 }} mediciones; escala de
0 a {{ max }} días.
</p>
<table
class="distribution route-table"
aria-label="Tiempo a diagnóstico por CIE-10"
>
<thead>
<tr>
<th>CIE-10 y descripción</th>
<th>Mediana</th>
<th>Mediciones</th>
<th>Q1–Q3</th>
</tr>
</thead>
<tbody>
@for (row of icd.rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
<span class="bar-track duration-track" aria-hidden="true">
<span
class="bar"
[style.width.%]="max ? (100 * row.median) / max : 0"
></span>
<span
class="quartile"
[style.left.%]="max ? (100 * (row.low ?? 0)) / max : 0"
></span>
<span
class="quartile"
[style.left.%]="max ? (100 * (row.high ?? 0)) / max : 0"
></span>
</span>
</th>
<td>{{ row.median }} días</td>
<td>{{ row.count }}</td>
<td>{{ row.low }}–{{ row.high }}</td>
</tr>
} @empty {
<tr>
<td colspan="4">Sin observaciones con código CIE-10 en el periodo.</td>
</tr>
}
</tbody>
</table>
}
}
}
</mat-card-content>
</mat-card>
}
@case ('results') {
<mat-card appearance="outlined" class="figure-card results-card">
<mat-card-content>
<h2 class="figure-card-title">{{ section.title }}</h2>
<div class="results-grid">
<section [attr.data-measure]="section.cytology.measure" class="cytology">
<h3 class="dist-title">{{ section.cytology.title }}</h3>
<mat-button-toggle-group
class="cytology-views"
aria-label="Lectura de los resultados citológicos"
[value]="cytologyView()"
(change)="cytologyView.set($event.value)"
>
<mat-button-toggle value="general">Distribución general</mat-button-toggle>
<mat-button-toggle value="scenario">Por escenario clínico</mat-button-toggle>
</mat-button-toggle-group>
@if (cytologyView() === 'general') {
<ng-container
*ngTemplateOutlet="
distBlock;
context: { $implicit: section.cytology, untitled: true }
"
/>
} @else {
@for (f of section.complement; track f.title) {
<div class="complement" [attr.data-figure]="f.kind">
<p class="state">
Los mismos resultados de la distribución citológica, según el estatus de
seguimiento de cada paciente al inicio del periodo; cada barra suma 100 % de
sus pacientes con resultado (n indica cuántas son).
</p>
@if (reports.isLoading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figureOf(f); as fig) {
@if (scenarioLegend(f); as legend) {
<ul class="legend" aria-label="Resultados citológicos">
@for (item of legend; track item.label) {
<li>
<span class="swatch" [style.background]="item.color"></span>
{{ item.label }}
</li>
}
</ul>
}
<app-plot [figure]="fig" [height]="scenarioHeight(fig)" />
} @else {
<p class="state">Sin pacientes con resultado en el periodo.</p>
}
</div>
}
}
</section>
<section [attr.data-measure]="section.hpv.measure">
<ng-container *ngTemplateOutlet="distBlock; context: { $implicit: section.hpv }" />
</section>
<section class="biopsy" [attr.data-measure]="section.biopsy.measure">
<ng-container
*ngTemplateOutlet="distBlock; context: { $implicit: section.biopsy }"
/>
</section>
</div>
</mat-card-content>
</mat-card>
}
@case ('confirmation') {
@if (confirmOf(section); as c) {
<mat-card appearance="outlined" class="figure-card confirmation-card">
<mat-card-content>
<h2 class="figure-card-title">{{ section.title }}</h2>
<p class="state confirmation-note">
No son tasas de referencias emitidas: cuentan procedimientos registrados
(colposcopía o biopsia) o solicitudes de biopsia registradas, y la citología previa
se asocia por fechas. Cada lectura tiene su propio denominador y su umbral
histológico.
</p>
<mat-button-toggle-group
class="confirmation-views"
aria-label="Perspectiva de la confirmación histopatológica"
[value]="confirmView()"
(change)="confirmView.set($event.value)"
>
<mat-button-toggle value="colposcopy">Colposcopía</mat-button-toggle>
<mat-button-toggle value="biopsy">Biopsia</mat-button-toggle>
</mat-button-toggle-group>
@if (confirmView() === 'colposcopy') {
<app-ppv-card
[embedded]="true"
[attr.data-measure]="section.colposcopy.measure"
[title]="c.colposcopy.title"
[note]="c.colposcopy.note"
[score]="c.colposcopy.score"
[detail]="c.colposcopy.detail"
[reading]="c.colposcopy.reading"
[loading]="reports.isLoading()"
[published]="c.colposcopy.published"
[modes]="section.colposcopy.modes"
/>
} @else {
<app-ppv-card
[embedded]="true"
[attr.data-measure]="section.biopsy.measure"
[title]="c.biopsy.title"
[note]="c.biopsy.note"
[score]="c.biopsy.score"
[detail]="c.biopsy.detail"
[reading]="c.biopsy.reading"
[loading]="reports.isLoading()"
[published]="c.biopsy.published"
[modes]="section.biopsy.modes"
[alternate]="c.requests"
/>
}
</mat-card-content>
</mat-card>
}
}
@case ('ppv') {
@if (cardOf(section); as c) {
<app-ppv-card
[attr.data-measure]="section.measure"
[title]="c.title"
[note]="c.note"
[score]="c.score"
[detail]="c.detail"
[reading]="c.reading"
[loading]="reports.isLoading()"
[published]="c.published"
[modes]="section.modes"
/>
}
}
@case ('measure-card') {
@if (cardOf(section); as c) {
<mat-card
appearance="outlined"
class="figure-card measure-card"
[attr.data-measure]="section.measure"
>
<mat-card-content>
<h2 class="figure-card-title">{{ c.title }}</h2>
@if (reports.isLoading()) {
<app-loading what="la medida" [figure]="true" />
} @else if (!c.published) {
<p class="state">Medida no publicada por el servidor.</p>
} @else if (c.reading?.error) {
<p class="state" role="alert">No se pudo consultar esta medida.</p>
} @else {
<p class="measure-score">{{ c.score }} · {{ c.detail }}</p>
@if (c.note) {
<p class="state">{{ c.note }}</p>
}
@for (f of c.figures; track f.title) {
<h3 class="figure-title">{{ f.title }}</h3>
<app-plot [figure]="f.figure" [height]="260" />
} @empty {
<p class="state">Sin pacientes en el periodo.</p>
}
}
</mat-card-content>
</mat-card>
}
}
@case ('tea-summary') {
@if (teaSummary(); as t) {
+163
View File
@@ -305,3 +305,166 @@ h2.box-subtitle {
margin: 0;
}
}
.route-head {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
justify-content: space-between;
}
.route-toggle {
flex-wrap: wrap;
max-width: 100%;
}
.route-values summary {
color: var(--color-text-secondary);
cursor: pointer;
padding: var(--space-2) 0;
}
.route-table td {
font-variant-numeric: tabular-nums;
}
.duration-track {
position: relative;
}
.duration-track .bar {
background: #42a77e;
}
.quartile {
background: #17324d;
height: 14px;
position: absolute;
top: -3px;
width: 2px;
}
.distribution {
border-collapse: collapse;
font-size: 13px;
width: 100%;
}
.distribution th {
font-weight: 500;
text-align: left;
}
.distribution td,
.distribution thead th:not(:first-child) {
padding-left: 12px;
text-align: right;
white-space: nowrap;
}
.distribution tbody th {
padding: 5px 0;
}
.distribution .group th {
background: #edf2f4;
font-weight: 600;
padding: 6px 8px;
}
.bar-track {
background: #eef1f3;
display: block;
height: 8px;
margin-top: 3px;
}
.bar {
display: block;
height: 100%;
}
.results-grid .distribution tbody th:has(.distribution-label) {
align-items: center;
display: flex;
gap: 10px;
}
.results-grid .distribution-label {
flex: 0 1 45%;
min-width: 0;
}
.results-grid .bar-track {
flex: 1;
height: 16px;
margin: 0;
min-width: 40px;
}
.measure-score {
font-weight: 500;
margin: var(--space-2) 0;
}
.route-card {
margin-top: 24px;
}
.route-card h3.route-title {
margin-top: 0;
}
.results-grid {
display: grid;
gap: 24px;
grid-template-columns: 1fr;
section {
min-width: 0;
}
p {
font-size: 13px;
margin: var(--space-2) 0;
}
}
h3.dist-title {
font-size: 16px;
font-weight: 500;
margin: var(--space-3) 0;
}
.results-grid .distribution td {
padding-left: 8px;
}
@media (min-width: 850px) {
.results-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.results-grid .biopsy {
grid-column: 1 / -1;
}
}
.hidden-note {
border-left: 3px solid var(--color-border);
padding-left: 8px;
}
.complement {
margin-top: var(--space-2);
}
.no-data {
color: var(--color-text-secondary);
display: block;
font-size: 12px;
font-weight: 400;
margin-top: 3px;
}
.cytology-views {
flex-wrap: wrap;
margin: var(--space-2) 0 var(--space-3);
max-width: 100%;
}
.legend {
display: flex;
flex-wrap: wrap;
font-size: 12px;
gap: 4px 14px;
list-style: none;
margin: var(--space-2) 0;
padding: 0;
}
.swatch {
display: inline-block;
height: 10px;
margin-right: 5px;
width: 10px;
}
.confirmation-views {
flex-wrap: wrap;
margin: var(--space-2) 0 var(--space-3);
max-width: 100%;
}
.confirmation-note {
font-size: 13px;
}
+110 -27
View File
@@ -8,8 +8,8 @@ import { MatSelectModule } from '@angular/material/select';
import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot';
import { DurationRow, durationRows } from './durations';
import { LAYOUTS } from './layout';
import { distribution, durationMax, durationRows, icdRows, withoutHidden } from './cacu-results';
import {
ageShare,
ageStack,
@@ -21,7 +21,7 @@ import {
scenarioBars,
shareDonut,
} from './figures';
import { FigureSpec, Kpi, PAGES, Section } from './pages';
import { DistSpec, FigureSpec, Kpi, PAGES, Section } from './pages';
import {
detail,
donut,
@@ -31,6 +31,7 @@ import {
periodLabel,
periods,
PeriodType,
PPV_NOTES,
reading,
Reading,
scoring,
@@ -38,8 +39,8 @@ import {
strataBars,
} from './measures';
import { Loading } from '../loading';
import { RouteCard } from './route-card';
import { ReadingsSection, Source } from './section';
import { PpvCard } from './ppv-card';
import { requestsAlternate } from './confirmation';
/** The period's indicators: the timeliness KPIs, the screening route, and a card per
* clinical measure with its figures. */
@@ -54,8 +55,7 @@ import { ReadingsSection, Source } from './section';
MatCardModule,
MatSelectModule,
Plot,
ReadingsSection,
RouteCard,
PpvCard,
],
templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss',
@@ -71,6 +71,12 @@ export class TabIndicadores {
/** The period the figures show (set by Aplicar). */
protected readonly applied = signal<string | undefined>(undefined);
protected readonly routeView = signal<'sample' | 'step'>('sample');
/** CaCu's route in three readings: cumulative from the sample, step by step, by ICD-10. */
/** The confirmation card's perspective. */
protected readonly confirmView = signal<'colposcopy' | 'biopsy'>('colposcopy');
/** The cytology column's two readings, one at a time. */
protected readonly cytologyView = signal<'general' | 'scenario'>('general');
protected readonly routeMode = signal<'sample' | 'step' | 'icd10'>('sample');
protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
@@ -118,11 +124,19 @@ export class TabIndicadores {
if (!params.period) return new Map<string, Reading | undefined>();
const found = await Promise.all(
params.measures.map(async (m) => {
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
try {
// Never `as-of`: CACU_BIOPSIA_SOLICITUD_CONFIRMACION cannot reconstruct the past.
const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!,
'reporting-period': params.period,
});
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const;
} catch (error) {
// A CaCu measure the server cannot serve leaves its own card to say so, not the page.
if (params.domain === 'cacu' && m.name?.startsWith('CACU_'))
return [m.name, { populations: {}, strata: {}, error: true } as Reading] as const;
throw error;
}
}),
);
return new Map(found);
@@ -197,15 +211,6 @@ export class TabIndicadores {
}
protected readonly name = name;
protected stepRows(section: Section, mode: 'sample' | 'step'): DurationRow[] {
if (section.kind !== 'route') return [];
return durationRows(
section[mode],
(code) => this.rd(code),
(code) => this.byName().has(code),
);
}
/** A measure's reading in the applied period, by code. */
protected rd(code: string): Reading | undefined {
return this.loaded()?.get(code);
@@ -277,15 +282,93 @@ export class TabIndicadores {
protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || '';
}
/** What a section of readings is drawn from. */
protected readonly of = computed<Source>(() => {
const found = this.loaded();
/** A clinical section's route or figures, drawn from the applied period's reports. */
/** A route's steps in one reading: days from the sample, or from the previous step. */
protected routeSteps(section: Section, mode: 'sample' | 'step') {
if (section.kind !== 'route') return [];
return section.steps.map((s) => ({
label: mode === 'step' ? (s.step ?? s.label) : s.label,
r: this.rd(mode === 'step' ? (s.stepMeasure ?? s.measure) : s.measure),
}));
}
/** The route's table: each step keeps its row, with or without measurements. */
protected stepRows(section: Section, mode: 'sample' | 'step') {
return durationRows(this.routeSteps(section, mode));
}
protected icdOf(section: Section) {
return section.kind === 'route' && section.modes
? { reading: this.rd(section.modes.icd), rows: icdRows(this.rd(section.modes.icd)) }
: undefined;
}
protected icdMax(rows: { median: number; high?: number }[]): number {
return Math.max(0, ...rows.map((r) => Math.max(r.median, r.high ?? 0)));
}
/** A distribution's table: its categories with their group lines, or none when the report
* does not add up (a zero is a zero; a report that is missing or inconsistent is not drawn).
* The categories the spec hides are left out of the rows only: the total, the percentages
* and the units outside stay as the report gives them. */
protected distOf(spec: DistSpec) {
const d = distribution(this.rd(spec.measure), spec.catalog);
if (!d) return undefined;
const { shown, max, hiddenCount } = withoutHidden(d, spec.hide);
const items = shown.flatMap((row) => [
...(spec.groups ?? [])
.filter((g) => g.before === row.code)
.map((g) => ({
kind: 'group' as const,
label: g.label,
count: d.rows.filter((r) => g.codes.includes(r.code)).reduce((n, r) => n + r.count, 0),
})),
{ kind: 'row' as const, ...row },
]);
return {
loading: this.reports.isLoading(),
reading: (code) => found?.get(code),
measure: (code) => this.byName().get(code),
...d,
items,
max,
hiddenCount,
};
});
}
/** The scale of a duration table, in days from zero. */
protected routeMax = durationMax;
/** The confirmation card: both PPV cards, the requests reading. */
protected confirmOf(section: Section) {
if (section.kind !== 'confirmation') return undefined;
return {
colposcopy: this.cardOf({ kind: 'ppv', ...section.colposcopy })!,
biopsy: this.cardOf({ kind: 'ppv', ...section.biopsy })!,
requests: requestsAlternate(
this.rd(section.biopsy.requests),
this.byName().has(section.biopsy.requests),
),
};
}
/** A measure's card: its title (the PPVs say they are not referrals), score and figures. */
protected cardOf(section: Section) {
if (section.kind !== 'measure-card' && section.kind !== 'ppv') return undefined;
const m = this.byName().get(section.measure);
const r = this.rd(section.measure);
const summary = section.kind === 'ppv' ? section.summary : undefined;
return {
published: !!m,
reading: r,
title: PPV_NOTES[section.measure]?.title ?? m?.title ?? section.measure,
note: PPV_NOTES[section.measure]?.note,
score: summary ? summary(r).score : m ? formatScore(m, r) : '',
detail: summary ? summary(r).detail : m ? detail(m, r) : '',
figures: this.figureSets().get(section.measure) ?? [],
};
}
/** The legend of the scenario figure, in the catalogue's order (the figure draws none). */
protected scenarioLegend(spec: FigureSpec) {
return spec.kind === 'scenario-bars'
? spec.catalog.categories.map((c) => ({ label: c.label, color: c.color }))
: undefined;
}
/** The scenario figure's height: a slim bar per scenario and room for the axis. */
protected scenarioHeight(fig: Figure): number {
const bars = (fig.data[0] as { y?: unknown[] } | undefined)?.y?.length ?? 1;
return 70 + bars * 46;
}
protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
+80 -53
View File
@@ -1,25 +1,28 @@
<div class="export-actions">
<button mat-stroked-button type="button" (click)="exportList('xlsx')" [disabled]="cannotExport()">
Exportar Excel (.xlsx)
</button>
<button mat-stroked-button type="button" (click)="exportList('pdf')" [disabled]="cannotExport()">
Exportar PDF
</button>
</div>
@if (exportMessage()) {
<p class="muted" role="alert">{{ exportMessage() }}</p>
}
<form class="filters card" (submit)="$event.preventDefault()">
<app-patient-search [(value)]="search" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
matInput
type="date"
[ngModel]="cutoff() || applied()"
(ngModelChange)="cutoff.set($event)"
name="cutoff"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad mínima</mat-label>
<input
matInput
type="number"
min="0"
max="120"
[ngModel]="ageFrom()"
(ngModelChange)="setAge(ageFrom, $event)"
name="ageFrom"
max="150"
step="1"
[ngModel]="ageMin()"
(ngModelChange)="ageMin.set($event)"
name="ageMin"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -28,10 +31,22 @@
matInput
type="number"
min="0"
max="120"
[ngModel]="ageTo()"
(ngModelChange)="setAge(ageTo, $event)"
name="ageTo"
max="150"
step="1"
[ngModel]="ageMax()"
(ngModelChange)="ageMax.set($event)"
name="ageMax"
/>
</mat-form-field>
<button mat-stroked-button type="button" (click)="clearAges()">Limpiar edades</button>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label>
<input
matInput
type="date"
[ngModel]="cutoff() || applied()"
(ngModelChange)="cutoff.set($event)"
name="cutoff"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -75,25 +90,13 @@
}
</mat-select>
</mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
@if (invalidAge()) {
<p class="muted" role="alert">
Indique edades enteras entre 0 y 150; la mínima no puede superar la máxima. El rango no está
aplicado.
</p>
}
@if (error()) {
@@ -117,7 +120,7 @@
<th>Paciente</th>
<th>Edad</th>
<th>Estatus de seguimiento</th>
<th>Etapas</th>
<th>Etapas del tamizaje</th>
<th>Última citología</th>
<th>Último resultado de VPH</th>
<th>Última biopsia</th>
@@ -133,8 +136,8 @@
<td>
<a
[routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
[queryParams]="{ corte: applied(), citologia: row.cytology?.date }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
[queryParams]="{ corte: applied(), muestra: row.cytology?.date }"
>{{ patientLabel(row.patient) }}</a
>
@if (row.curp) {
<div class="muted curp">{{ row.curp }}</div>
@@ -142,23 +145,39 @@
</td>
<td>
{{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup }}</small>
<small>Grupo: {{ row.ageGroup || 'No disponible' }}</small>
</td>
<td>{{ name(row.status) }}</td>
<td>
<app-stages [stages]="row.stages" />
<button
mat-button
type="button"
[attr.aria-expanded]="opened() === row.patient.id"
(click)="toggle(row)"
>
Detalle
</button>
<div class="stage-compact">
<app-stages
[sample]="row.cytology?.date"
[report]="row.cytology?.result ? row.cytology?.reportDate : undefined"
[cutoff]="applied()"
[facts]="row.stageFacts"
/>
<button
class="stage-toggle"
type="button"
[attr.aria-label]="
expanded() === row.patient.id ? 'Ocultar etapas' : 'Mostrar etapas'
"
[attr.aria-expanded]="expanded() === row.patient.id"
(click)="toggle(row.patient.id)"
>
<span [class.open]="expanded() === row.patient.id" aria-hidden="true">⌄</span>
</button>
</div>
</td>
<td>
@if (row.cytology; as c) {
{{ result(c) }}
{{
c.result
? name(c.result)
: c.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}}
<small>Fecha: {{ c.date }}</small>
<small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
} @else {
@@ -208,9 +227,17 @@
<td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr>
@if (opened() === row.patient.id) {
<tr class="stage-detail">
<td colspan="11"><app-stages [stages]="row.stages" [detail]="true" /></td>
@if (expanded() === row.patient.id) {
<tr class="stage-panel">
<td colspan="11">
<app-stages
[sample]="row.cytology?.date"
[report]="row.cytology?.result ? row.cytology?.reportDate : undefined"
[cutoff]="applied()"
[facts]="row.stageFacts"
[detail]="true"
/>
</td>
</tr>
}
} @empty {
+47
View File
@@ -60,3 +60,50 @@ a {
.window {
margin: 4px 0 8px;
}
.export-actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
justify-content: flex-end;
margin-bottom: var(--space-3);
}
.stage-compact {
align-items: center;
display: flex;
}
.stage-toggle {
background: transparent;
border: 0;
color: #385c6c;
cursor: pointer;
display: grid;
flex: 0 0 32px;
height: 32px;
padding: 0;
place-items: center;
width: 32px;
}
.stage-toggle:focus-visible {
outline: 2px solid #2778b8;
outline-offset: 2px;
}
.stage-toggle span {
display: block;
font-size: 18px;
line-height: 1;
transition: transform 120ms ease;
}
.stage-toggle span.open {
transform: rotate(180deg);
}
// the detailed stages of one patient, across the table
.stage-panel td {
background: var(--mat-sys-surface-container-low, #f6f8f9);
}
+204 -73
View File
@@ -1,13 +1,6 @@
import { DecimalPipe } from '@angular/common';
import {
Component,
computed,
inject,
input,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -15,19 +8,25 @@ import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { downloadDocument } from '../export-document';
import { Fhir } from '../fhir';
import { saveExcel, savePdf } from '../export';
import { Stages } from '../paciente/stages';
import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
import { Stages, stages } from '../paciente/stages';
import { patientLabel, Row, rows, windowStart } from './follow-up';
import { name } from './measures';
import { PatientSearch, patientSearch } from './patient-search';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
const SORTS: Record<string, string> = {
'-recent': 'Estudio más reciente',
'-risk-cin2': 'Mayor riesgo de LIEAG+',
'-risk-cancer': 'Mayor riesgo de cáncer',
};
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status,
* results and current risks, in the order asked for. */
/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her age, status, the
* stages of her screening, results and current risks, in the order asked for; and the same
* query as a PDF or an Excel file. */
@Component({
selector: 'app-tab-riesgos',
imports: [
@@ -47,6 +46,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
})
export class TabRiesgos {
private readonly fhir = inject(Fhir);
private readonly http = inject(HttpClient);
readonly domain = input.required<string>();
protected readonly cutoff = signal<string>('');
@@ -57,37 +57,56 @@ export class TabRiesgos {
protected readonly size = signal(20);
/** "Buscar paciente": her name, CURP or record number, as applied. */
protected readonly search = signal('');
/** Completed years at the cut-off (none: no limit). */
protected readonly ageFrom = signal<number | null>(null);
protected readonly ageTo = signal<number | null>(null);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** Whose stages are shown in full. */
protected readonly opened = signal<string | undefined>(undefined);
/** Completed years at the cut-off, from and to (none: no limit). */
protected readonly ageMin = signal<number | null>(null);
protected readonly ageMax = signal<number | null>(null);
/** The patient whose stages are open under her row. */
protected readonly expanded = signal<string | undefined>(undefined);
/** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly exporting = signal(false);
protected readonly exportMessage = signal('');
protected readonly statuses = STATUSES;
protected readonly name = name;
protected readonly result = cytologyResult;
protected readonly patientLabel = patientLabel;
/** Whole years between 0 and 150, and the minimum not above the maximum; else the range is
* not applied and the page says so. */
protected readonly invalidAge = computed(() => {
const [low, high] = [this.ageMin(), this.ageMax()];
const bad = (n: number | null) => n !== null && (!Number.isInteger(n) || n < 0 || n > 150);
return bad(low) || bad(high) || (low !== null && high !== null && low > high);
});
private readonly ages = computed(() =>
this.invalidAge()
? {}
: {
'follow-up-age-min': this.ageMin() ?? undefined,
'follow-up-age-max': this.ageMax() ?? undefined,
},
);
/** The list as it is asked for, whatever the page. */
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
birthdate: bornFor(this.cutoff(), this.ageFrom(), this.ageTo()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
loader: ({ params: { domain, query, size } }) => {
params: () => ({
domain: this.domain(),
'follow-up-window': this.window(),
...patientSearch(this.search()),
...this.ages(),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
this.expanded.set(undefined);
return this.fhir.search(domain, 'Patient', {
...params,
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
},
});
protected readonly loading = signal(false);
@@ -131,41 +150,12 @@ export class TabRiesgos {
protected retry(): void {
this.first.reload();
}
/** Ages are told at the cut-off: the one shown becomes the one asked for. */
protected setAge(age: WritableSignal<number | null>, years: number | null): void {
if (!this.cutoff()) this.cutoff.set(this.applied());
age.set(years);
protected toggle(id: string | undefined): void {
this.expanded.set(this.expanded() === id ? undefined : id);
}
/** The whole list, not the page shown, as a file. */
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
const cutoff = this.applied();
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
const pages = await this.fhir.all(this.domain(), 'Patient', asked);
const start = windowStart(cutoff, this.window());
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon()));
const sheet = followUpSheet(all, [
['Ventana consultada', `${start} al ${cutoff}`],
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`],
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`],
['Búsqueda', this.search() || 'Ninguna'],
['Horizonte de la probabilidad (años)', `${this.horizon()}`],
]);
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu');
else await savePdf([sheet], 'seguimiento-cacu', true);
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected toggle(row: Row): void {
this.opened.set(this.opened() === row.patient.id ? undefined : row.patient.id);
protected clearAges(): void {
this.ageMin.set(null);
this.ageMax.set(null);
}
protected has(relation: 'next' | 'previous'): boolean {
@@ -183,4 +173,145 @@ export class TabRiesgos {
this.loading.set(false);
}
}
/** What an export may not start from: no list yet, a range not applied, or a query in motion. */
protected readonly cannotExport = computed(
() =>
this.exporting() ||
!this.page() ||
this.invalidAge() ||
this.first.isLoading() ||
this.loading(),
);
/** The whole query (not the page on screen) as a PDF or an Excel file, with the filters it
* was asked with. The server's limits are the ones that decide; the list is read again
* whole and must still be the query it was when the button was pressed. */
protected async exportList(format: 'xlsx' | 'pdf'): Promise<void> {
if (this.cannotExport() || !this.applied()) return;
const total = this.page()!.total ?? 0;
const cutoff = this.applied();
const months = this.window();
const horizon = this.horizon();
this.exporting.set(true);
this.exportMessage.set('');
try {
const limits = await firstValueFrom(
this.http.get<{ xlsx_limit: number; pdf_limit: number }>('/api/cacu/exports/capabilities'),
);
const limit = format === 'pdf' ? limits.pdf_limit : limits.xlsx_limit;
if (total > limit) {
this.exportMessage.set(
`La consulta tiene ${total} pacientes; el límite para ${format.toUpperCase()} es ${limit}. Ajuste los filtros.`,
);
return;
}
const params = {
'follow-up-window': months,
'follow-up-cutoff': cutoff,
'follow-up-status': this.status() || undefined,
'risk-horizon': horizon,
_sort: this.sort(),
_count: 200,
...patientSearch(this.search()),
...this.ages(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
};
const pages = await this.fhir.all(this.domain(), 'Patient', params);
const all = pages.flatMap((p) => rows(p, windowStart(cutoff, months), cutoff, horizon));
if (
all.length !== total ||
new Set(all.map((r) => r.patient.id)).size !== total ||
pages.some((p) => p.total !== total)
)
throw new Error('La consulta cambió durante la exportación; vuelva a intentarlo.');
await downloadDocument(this.http, format, this.document(all, cutoff, months, horizon, total));
} catch (error) {
this.exportMessage.set(
error instanceof Error ? error.message : 'No se pudo generar la exportación.',
);
} finally {
this.exporting.set(false);
}
}
/** The document: the parameters of the query and one row per patient, as the list shows her. */
private document(all: Row[], cutoff: string, months: number, horizon: number, total: number) {
const pct = (n?: number) => (n === undefined ? 'No disponible' : `${(100 * n).toFixed(1)} %`);
const years = `${horizon} ${horizon === 1 ? 'año' : 'años'}`;
const routes = all.map((r) =>
stages(
r.cytology?.date,
r.cytology?.result ? r.cytology.reportDate : undefined,
cutoff,
r.stageFacts,
),
);
return {
title: 'Resultados de seguimiento',
parameters: [
['Fecha de corte', cutoff],
[
'Ventana consultada',
`${windowStart(cutoff, months)} al ${cutoff} (${months} ${months === 1 ? 'mes' : 'meses'})`,
],
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
['Orden', SORTS[this.sort()] ?? this.sort()],
['Horizonte de la probabilidad', years],
['Nombre o identificador', this.search().trim() || 'Todos'],
['Edad mínima (años)', String(this.ageMin() ?? 'Sin límite')],
['Edad máxima (años)', String(this.ageMax() ?? 'Sin límite')],
['Registros', String(total)],
],
columns: [
'Paciente',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
`Riesgo LIEAG+ a ${years}`,
`Riesgo de cáncer a ${years}`,
'Días de toma a diagnóstico',
],
row_stages: routes.map((route) =>
route.map((s) => ({
state: s.state,
...(s.provenance ? { provenance: s.provenance } : {}),
...(s.date ? { date: s.date } : {}),
})),
),
rows: all.map((r, i) => [
`${patientLabel(r.patient)}${r.curp ? '\n' + r.curp : ''}`,
r.age === undefined ? 'No disponible' : `${r.age}`,
name(r.status),
routes[i]
.map(
(s) =>
`${s.label}: ${s.state}${s.date ? ' ' + s.date : ''}${s.provenance ? ' (' + s.provenance + ')' : ''}`,
)
.join('\n'),
r.cytology
? `${r.cytology.date} · ${
r.cytology.result
? name(r.cytology.result)
: r.cytology.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}`
: 'No disponible',
r.hpv
? `${r.hpv.positive ? 'Positivo' : 'Negativo'}${r.hpv.types1618 ? ' (16/18)' : ''}`
: 'No disponible',
r.biopsy
? `${r.biopsy.date} · ${name(r.biopsy.histology ?? '') || 'Sin grado'}`
: 'No disponible',
pct(r.risk.cin2),
pct(r.risk.cancer),
String(r.daysToDiagnosis ?? 'No disponible'),
]),
};
}
}
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest';
import { Reading } from './measures';
import { VPH_MODES, vphDonut, vphGenotypes, vphGroups, vphSummary } from './vph';
const n = (count: number) => ({ 'initial-population': count });
const report = (strata: Reading['strata'], population = 10): Reading => ({
populations: { 'initial-population': population },
strata,
});
const base = { category: { negative: n(7), positive: n(3) } };
describe('CACU_VPH readings (patients by their latest HPV result)', () => {
it('summarises the patients and how they split, and does not invent when it does not add up', () => {
expect(vphSummary(report(base))).toEqual({
score: '10 pacientes',
detail: 'Negativo: 7 (70.0 %) · Positivo: 3 (30.0 %).',
});
expect(vphSummary(report({ category: { negative: n(7) } })).score).toBe('Sin dato');
expect(vphSummary(undefined).score).toBe('Sin dato');
// a real zero is a zero, not a missing report
expect(vphSummary(report({ category: {} }, 0)).score).toBe('0 pacientes');
expect(vphDonut(report({ category: {} }, 0))).toBeUndefined();
});
it('draws the whole as negative and positive in the HPV colours of the page', () => {
const fig = vphDonut(report(base))!;
const pie = fig.data[0] as { values: number[]; marker: { colors: string[] } };
expect(pie.values).toEqual([7, 3]);
expect(pie.marker.colors).toEqual(['#42a77e', '#a8c243']);
});
it('gives each group its positives over its patients with a result, in age order', () => {
const rows = vphGroups(
report({
...base,
'age_group-category': {
'45-54|positive': n(2),
'45-54|negative': n(2),
'25-34|negative': n(4),
'<25|positive': n(1),
},
}),
'age_group',
);
expect(rows.map((r) => r.code)).toEqual(['<25', '25-34', '45-54']);
expect(rows[2]).toMatchObject({ numerator: 2, denominator: 4, percent: 50 });
// a group with patients and no positive is a zero rate, not a missing one
expect(rows[1]).toMatchObject({ numerator: 0, denominator: 4, percent: 0 });
expect(vphGroups(report(base), 'age_group')).toEqual([]);
});
it('keeps "no data" neutral and the rounds excluding', () => {
const rows = vphGroups(
report({
...base,
'screening_round-category': {
'no_data|negative': n(1),
'initial|positive': n(1),
'subsequent|negative': n(2),
},
}),
'screening_round',
);
expect(rows.map((r) => r.code)).toEqual(['initial', 'subsequent', 'no_data']);
expect(rows[2]).toMatchObject({ label: 'Sin dato', color: '#C9CDD2' });
});
it('reads each genotype over the patients whose genotype was reported, and skips an unpublished one', () => {
const rows = vphGenotypes(report({ ...base, hpv_16: { negative: n(5), positive: n(2) } }));
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
label: 'VPH 16',
numerator: 2,
denominator: 7,
color: '#df8640',
});
});
it('offers the whole and the four breakdowns the measure publishes', () => {
expect(VPH_MODES.map((m) => m.id)).toEqual(['total', 'age', 'status', 'genotype', 'round']);
expect(VPH_MODES.every((m) => m.caption.length > 20)).toBe(true);
});
});
+188
View File
@@ -0,0 +1,188 @@
import type { Figure } from '../plot';
import { HPV_REPORTS } from './cacu-results';
import { name, Reading } from './measures';
import { PpvMode, PpvRow } from './ppv';
/** CACU_VPH counts patients: each one by her latest sample with an HPV result in the period. It
* is not CACU_VPH_GENOTIPO, which counts reports. Its readings are the ones the report publishes:
* the result (the `category` stratum), that result inside each group of a stratifier (the report's
* `<stratum>-category` cells), and the genotypes 16 and 18 (strata of their own). */
const color = (code: string) => HPV_REPORTS.find((r) => r[0] === code)![2];
const NEGATIVE = color('negative');
const POSITIVE = color('positive_other');
const NEUTRAL = '#C9CDD2';
const STEEL = '#5F7F9A';
const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0;
const count = (cell: Record<string, number> | undefined) => cell?.['initial-population'];
/** The patients by result, when the report adds up to its population. */
function results(reading: Reading | undefined) {
const cells = reading?.strata['category'];
const total = reading?.populations['initial-population'];
if (!cells || !whole(total)) return undefined;
const negative = count(cells['negative']) ?? 0;
const positive = count(cells['positive']) ?? 0;
const other = Object.keys(cells).some((c) => c !== 'negative' && c !== 'positive');
return whole(negative) && whole(positive) && !other && negative + positive === total
? { total, negative, positive }
: undefined;
}
const share = (n: number, of: number) => ((100 * n) / of).toFixed(1);
/** The card's heading figures: patients with a result, and how they split. */
export function vphSummary(reading: Reading | undefined): { score: string; detail: string } {
const r = results(reading);
if (!r) return { score: 'Sin dato', detail: '' };
if (!r.total) return { score: '0 pacientes', detail: 'Sin pacientes en el periodo.' };
return {
score: `${r.total} pacientes`,
detail: `Negativo: ${r.negative} (${share(r.negative, r.total)} %) · Positivo: ${r.positive} (${share(r.positive, r.total)} %).`,
};
}
/** The whole: negative and positive patients as a donut. */
export function vphDonut(reading: Reading | undefined): Figure | undefined {
const r = results(reading);
if (!r?.total) return undefined;
return {
data: [
{
type: 'pie',
hole: 0.62,
labels: ['Negativo', 'Positivo'],
values: [r.negative, r.positive],
sort: false,
direction: 'clockwise',
textinfo: 'value+percent',
textposition: 'outside',
marker: { colors: [NEGATIVE, POSITIVE] },
},
],
layout: {
height: 260,
showlegend: true,
margin: { t: 16, r: 8, b: 16, l: 8 },
legend: { orientation: 'h' },
},
};
}
const AGES = ['<25', '25-34', '35-44', '45-54', '55-64', '65+'];
const ORDER: Record<string, [code: string, color: string][]> = {
age_group: AGES.map((c) => [c, STEEL]),
follow_up_status: [
['pre_colposcopy', STEEL],
['post_colposcopy', '#8FA7BB'],
['post_treatment', '#B5C5D3'],
['case', '#9AA3AB'],
],
screening_round: [
['initial', STEEL],
['subsequent', '#8FA7BB'],
['no_data', NEUTRAL],
],
};
const groupLabel = (group: string) =>
group === 'no_data'
? 'Sin dato'
: name(group) === group
? group.replace('-', ' a ')
: name(group);
/** A group's positive patients over its patients with a result, from the report's crossed cells.
* A group the report does not list is not drawn; absent is not a zero. */
export function vphGroups(reading: Reading | undefined, stratum: string): PpvRow[] {
const cells = reading?.strata[`${stratum}-category`];
if (!cells) return [];
const groups = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
const order = ORDER[stratum] ?? [];
const known = order.map(([c]) => c);
return [...known.filter((g) => groups.includes(g)), ...groups.filter((g) => !known.includes(g))]
.map((group) => {
const negative = count(cells[`${group}|negative`]) ?? 0;
const positive = count(cells[`${group}|positive`]) ?? 0;
const denominator = negative + positive;
return {
code: group,
label: groupLabel(group),
color: order.find(([c]) => c === group)?.[1] ?? STEEL,
numerator: positive,
denominator,
percent: denominator ? (100 * positive) / denominator : undefined,
};
})
.filter((row) => whole(row.numerator) && whole(row.denominator));
}
/** Genotype 16 and 18: positives over the patients whose genotype was reported (its own stratum). */
export function vphGenotypes(reading: Reading | undefined): PpvRow[] {
return (
[
['hpv_16', 'VPH 16', color('positive_16')],
['hpv_18', 'VPH 18', color('positive_18')],
] as const
).flatMap(([stratum, label, tone]) => {
const cells = reading?.strata[stratum];
if (!cells) return [];
const negative = count(cells['negative']) ?? 0;
const positive = count(cells['positive']) ?? 0;
if (!whole(negative) || !whole(positive)) return [];
const denominator = negative + positive;
return [
{
code: stratum,
label,
color: tone,
numerator: positive,
denominator,
percent: denominator ? (100 * positive) / denominator : undefined,
},
];
});
}
const POSITIVES = '% positivas';
const OF_RESULT = 'Positivas sobre las pacientes con resultado de VPH del grupo (n/N)';
/** The readings of CACU_VPH: the whole, and each breakdown the measure publishes. */
export const VPH_MODES: PpvMode[] = [
{
id: 'total',
label: 'Total',
figure: vphDonut,
caption:
'Una paciente por periodo, por su última muestra con resultado de VPH: negativas y positivas sobre todas ellas.',
},
{
id: 'age',
label: 'Por grupo de edad',
rows: (r) => vphGroups(r, 'age_group'),
percentLabel: POSITIVES,
caption: `${OF_RESULT}. Los grupos son excluyentes.`,
},
{
id: 'status',
label: 'Por estatus de seguimiento',
rows: (r) => vphGroups(r, 'follow_up_status'),
percentLabel: POSITIVES,
caption: `${OF_RESULT}. El estatus es el de la paciente al inicio del periodo; los grupos son excluyentes.`,
},
{
id: 'genotype',
label: 'Por genotipo',
rows: vphGenotypes,
percentLabel: POSITIVES,
caption:
'Positivas para el genotipo sobre las pacientes con ese genotipo reportado; el denominador cambia por genotipo y una paciente puede ser positiva para ambos.',
},
{
id: 'round',
label: 'Por tamizaje inicial o subsecuente',
rows: (r) => vphGroups(r, 'screening_round'),
percentLabel: POSITIVES,
caption: `${OF_RESULT}. Cada paciente está en un solo grupo; «Sin dato»: sin clasificación de tamizaje inicial o subsecuente.`,
},
];
+93 -101
View File
@@ -1,4 +1,14 @@
<section class="page">
@if (domain() === 'cacu' && patient()) {
<div class="export-actions">
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="exportPatient()">
Exportar ficha PDF
</button>
</div>
}
@if (exportError()) {
<p class="muted" role="alert">{{ exportError() }}</p>
}
<a mat-button [routerLink]="['/indicadores', domain()]"
><mat-icon>arrow_back</mat-icon> Regresar</a
>
@@ -7,6 +17,9 @@
} @else if (patient(); as p) {
<h1>
{{ identity().name ?? 'Paciente' }} <code class="muted id">{{ p.id!.slice(0, 10) }}</code>
@if (domain() === 'cacu') {
· Edad: {{ age() ?? 'No disponible' }}
}
</h1>
<dl class="summary">
<div>
@@ -21,12 +34,6 @@
<dt>Fecha de nacimiento</dt>
<dd>{{ p.birthDate ?? 'Sin dato' }}</dd>
</div>
@if (stages()) {
<div>
<dt>Edad</dt>
<dd>{{ age() ?? 'Sin dato' }}</dd>
</div>
}
<div>
<dt>Sexo</dt>
<dd>
@@ -110,25 +117,19 @@
<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>
@if (domain() === 'cacu') {
<app-stages
[sample]="sample()"
[report]="sampleReportDate()"
[cutoff]="cutoff()"
[facts]="sampleFacts()"
[detail]="true"
/>
<p class="muted route-note">
Etapas de la citología{{ sample() ? ' del ' + sample() : '' }} a la fecha de corte
{{ cutoff() }}. «Inferida temporalmente» es una asociación por cercanía de fechas, no
un vínculo clínico confirmado; «Desconocida» indica que no hay dato.
</p>
}
<table class="plain">
<thead>
@@ -178,19 +179,7 @@
<td class="nowrap">{{ t.date }}</td>
<td>{{ t.kind }}</td>
<td class="nowrap">{{ t.reported ?? 'Pendiente' }}</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>
<td>{{ t.results.join(' · ') || '—' }}</td>
</tr>
} @empty {
<tr>
@@ -202,65 +191,76 @@
</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 [groups]="groups()" />
@if (reference.value(); as ref) {
<app-reference-risk [view]="ref" />
@if (domain() === 'cacu') {
<p class="muted">
Divisiones numéricas descriptivas; no representan umbrales clínicos.
</p>
@for (model of riskScales(); track model.model) {
<h3>{{ model.model }} · fecha índice {{ model.index }}</h3>
@for (
scale of [
{ label: 'Riesgo inmediato (al índice)', value: model.immediate },
{ label: 'Riesgo a 5 años', value: model.five },
];
track scale.label
) {
<div class="risk-scale">
<p>
<strong>{{ scale.label }}</strong>
@if (scale.value; as v) {
@if (v.low !== undefined && v.high !== undefined) {
· IC 95 %: {{ v.low * 100 | number: '1.1-2' }}–{{
v.high * 100 | number: '1.1-2'
}}
%
}
} @else {
· No disponible
}
</p>
<div class="risk-plot" [class.unavailable]="!scale.value">
<div class="risk-line" aria-hidden="true"></div>
@if (scale.value; as v) {
<span
class="risk-marker"
[style.left.%]="v.value * 100"
aria-hidden="true"
></span>
<strong
class="risk-value"
[style.left]="'clamp(2.5rem, ' + v.value * 100 + '%, calc(100% - 2.5rem))'"
>{{ v.value * 100 | number: '1.1-2' }} %</strong
>
}
</div>
<div class="risk-labels">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span
><span>100 %</span>
</div>
</div>
}
} @empty {
@for (label of ['Riesgo inmediato', 'Riesgo a 5 años']; track label) {
<div class="risk-scale">
<p>
<strong>{{ label }}</strong> · No disponible
</p>
<div class="risk-plot unavailable">
<div class="risk-line" aria-hidden="true"></div>
</div>
<div class="risk-labels">
<span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span
><span>100 %</span>
</div>
</div>
}
<p class="muted">Ningún modelo vigente la ha evaluado.</p>
}
}
@if (models().length) {
<table class="plain">
@@ -294,15 +294,7 @@
}
</tbody>
</table>
<details class="curves" open data-section="curvas">
<summary>Curvas de probabilidad con su intervalo</summary>
<ul class="curve-text">
@for (t of curveText(); track $index) {
<li>{{ t }}</li>
}
</ul>
<app-plot [figure]="curve()" [height]="300" />
</details>
<app-plot [figure]="curve()" [height]="300" />
} @else {
<p class="muted">Sin evaluación de un modelo en producción.</p>
}
+50 -24
View File
@@ -110,31 +110,57 @@ h1 .id {
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;
}
}
// the risk scale: four equal numeric parts of 0 to 100 %, descriptive, not clinical thresholds
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
.curves {
border: 1px solid var(--color-border);
border-radius: 6px;
margin-top: 12px;
padding: 8px 12px;
summary {
cursor: pointer;
font-weight: 500;
p {
margin: 0;
}
}
.curve-text {
margin: 8px 0;
padding-left: 18px;
.risk-plot {
padding-top: 24px;
position: relative;
}
.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;
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;
}
+232 -143
View File
@@ -1,4 +1,5 @@
import { DecimalPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -12,6 +13,7 @@ import type {
Procedure,
RiskAssessment,
} from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { Api } from '../api/api';
import { studies as eegStudies } from '../api/fn/eeg/studies';
import { study as eegStudy } from '../api/fn/eeg/study';
@@ -19,18 +21,16 @@ import { readReport$Json } from '../api/fn/models/read-report-json';
import type { Domain } from '../api/models/domain';
import { code, EXT, ext, Fhir, label, resources } from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { savePdf } from '../export';
import { recordSheets } from './record-sheets';
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, split } from './record-groups';
import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk';
import { curveFigure, curveText } from './risk-curve';
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 { downloadDocument } from '../export-document';
import {
ageGroup,
CAMA_AGE_GROUPS,
camaRows,
CURP,
exactAge,
patientLabel,
patientName,
} from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
import {
BIOMARKER_NAMES,
@@ -45,6 +45,8 @@ import type { Relation } from '../api/models/relation';
import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores';
import { horizonRisk } from './risk-scale';
import { daysBetween, intervalText, routeFacts, stages, Stages } from './stages';
/** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string {
@@ -58,15 +60,6 @@ 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({
@@ -74,15 +67,13 @@ function facts(observations: Observation[]): Fact[] {
imports: [
Factores,
Loading,
Stages,
DecimalPipe,
MatButtonModule,
MatCardModule,
MatIconModule,
RouterLink,
Plot,
RiskScales,
ReferenceRisk,
Stages,
],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
@@ -90,25 +81,39 @@ function facts(observations: Observation[]): Fact[] {
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. */
readonly ventana = input<string>();
readonly corte = input<string>();
/** CaCu: the day of the cytology the list showed of her. */
readonly citologia = input<string>();
/** CaCu: the sample (its day) whose route the list showed. */
readonly muestra = input<string>();
private readonly http = inject(HttpClient);
protected readonly exporting = signal(false);
protected readonly exportError = signal('');
private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }),
loader: async ({ params: { domain, id } }) => {
params: () => ({ domain: this.domain(), id: this.id(), cutoff: this.corte() }),
loader: async ({ params: { domain, id, cutoff } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 };
const cacu = domain === 'cacu' && !!cutoff;
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
this.fhir.read<Patient>(domain, 'Patient', id),
// opened from the list: her status and age as of its cut-off
cacu
? this.fhir
.search(domain, 'Patient', { _id: id, 'follow-up-cutoff': cutoff })
.then((bundle) => {
const found = resources<Patient>(bundle, 'Patient', 'match')[0];
if (!found) throw new Error('Paciente no encontrada');
return found;
})
: this.fhir.read<Patient>(domain, 'Patient', id),
this.fhir.all(domain, 'Condition', subject),
this.fhir.all(domain, 'Procedure', subject),
this.fhir.all(domain, 'DiagnosticReport', subject),
this.fhir.all(domain, 'DiagnosticReport', {
...subject,
'stage-cutoff': cacu ? cutoff : undefined,
}),
this.fhir.all(domain, 'Observation', subject),
this.fhir.all(domain, 'RiskAssessment', subject),
]);
@@ -146,82 +151,6 @@ export class Paciente {
})),
].sort((a, b) => b.date.localeCompare(a.date));
});
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(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
(r) => code(r.code) === 'cervical_cytology',
);
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
});
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()) : [],
);
/** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API
* answers 404 while the feature is off: then nothing is shown. */
protected readonly reference = resource({
params: () =>
this.domain() === 'cacu'
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
: undefined,
loader: async ({ params }): Promise<ReferenceView | undefined> => {
try {
const answer = await firstValueFrom(
this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$reference-risk`,
{
params: Object.fromEntries(
Object.entries({ cutoff: params.cutoff, sample: params.sample }).filter(
([, v]) => !!v,
),
) as Record<string, string>,
},
),
);
return referenceView(answer);
} catch {
return undefined;
}
},
});
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** CaCu: her record as a PDF. */
protected async save(): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
const { name: who, curp, numbers } = this.identity();
const facts: [string, string | undefined][] = [
['Nombre', who],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', this.patient()?.birthDate],
['Edad', this.age()?.toString()],
['Estatus de seguimiento', this.status()],
['Fecha de corte', this.cutoff()],
];
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.forms(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
@@ -229,45 +158,19 @@ 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,
results: found.results,
findings: found.findings,
// "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}`;
}),
};
});
});
/** 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>();
@@ -466,18 +369,204 @@ export class Paciente {
}
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
protected readonly curve = computed<Figure>(() => curveFigure(this.models(), this.top()));
protected readonly curveText = computed(() => curveText(this.models()));
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',
},
},
};
});
private top(): number {
return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
}
protected readonly name = name;
protected readonly levelNames = LEVEL_NAMES;
// ---- CaCu: the screening route of one cytology, her age, and her risks ----
/** The cut-off her route and age are told at: the list's, else today. */
protected readonly cutoff = computed(() => this.corte() ?? new Date().toISOString().slice(0, 10));
protected readonly age = computed(() => exactAge(this.patient()?.birthDate, this.cutoff()));
/** The cytology whose route is drawn: the one the list opened her at, else her latest. */
private readonly routeReport = computed(() => {
const cytologies = (this.data.value()?.reports ?? []).filter(
(r) => code(r.code) === 'cervical_cytology',
);
return (
cytologies.find((r) => r.effectiveDateTime === this.muestra()) ??
(this.muestra() ? undefined : cytologies[0])
);
});
protected readonly sample = computed(() => this.routeReport()?.effectiveDateTime);
/** Her report day, only when the cytology has a result. */
protected readonly sampleReportDate = computed(() => {
const d = this.data.value();
const report = this.routeReport();
const hasResult = (report?.result ?? []).some((ref) => {
const o = d?.observations.get(ref.reference?.split('/')[1]);
return code(o?.code) === 'cervical_cytology.result' && !!code(o?.valueCodeableConcept);
});
return hasResult ? ext(report, 'report-date')?.valueDate : undefined;
});
protected readonly sampleFacts = computed(() => routeFacts(this.routeReport()));
/** The route as drawn, for the export too. */
protected readonly route = computed(() =>
stages(this.sample(), this.sampleReportDate(), this.cutoff(), this.sampleFacts()),
);
/** The immediate (index) and five-year risk of each CaCu risk model, by the horizons the
* model published: a horizon it did not publish is absent, never a zero. The title is the
* model's own, so the outcome is the one it predicts. */
protected readonly riskScales = computed(() => {
const latest = new Map<string, RiskAssessment>();
for (const risk of this.data.value()?.risks ?? []) {
const key = code(risk.method) ?? '';
if (!key.startsWith('cacu.cin2') && !key.startsWith('cacu.cancer')) continue;
const known = latest.get(key);
if (!known || (known.occurrenceDateTime ?? '') < (risk.occurrenceDateTime ?? ''))
latest.set(key, risk);
}
return [...latest.entries()].map(([model, risk]) => ({
model: risk.method?.coding?.[0]?.display ?? risk.method?.text ?? model,
index: risk.occurrenceDateTime,
immediate: horizonRisk(risk, 0),
five: horizonRisk(risk, 5),
}));
});
protected readonly daysBetween = daysBetween;
/** Her file as a PDF: identity, the route, history, tests and the risk scales, as on screen. */
protected async exportPatient(): Promise<void> {
const patient = this.patient();
if (!patient) return;
this.exporting.set(true);
this.exportError.set('');
try {
await firstValueFrom(this.http.get('/api/cacu/exports/capabilities'));
const route = this.route();
const inferred = (s?: { provenance?: string }) => s?.provenance === 'Inferida temporalmente';
const timeline = route.map((s, i) => ({
state: s.state,
label: s.label,
...(s.provenance ? { provenance: s.provenance } : {}),
...(s.date ? { date: s.date } : {}),
prev: intervalText(
i ? route[i - 1].date : undefined,
s.date,
inferred(s) || (i > 0 && inferred(route[i - 1])),
),
start: intervalText(route[0].date, s.date, inferred(s)),
}));
const lines = (s: (typeof route)[number], i: number) =>
`${s.label}: ${s.state}${s.provenance ? ' · ' + s.provenance : ''}; fecha ${s.date ?? '—'}; ` +
`desde anterior ${timeline[i].prev}; desde toma ${timeline[i].start}`;
const entries: string[][] = [
['Identificador', patient.id ?? 'No disponible'],
['Paciente', patientLabel(patient)],
['CURP', this.identity().curp ?? 'No disponible'],
['Expedientes', this.identity().numbers.join(', ') || 'No disponible'],
['Nacimiento', patient.birthDate ?? 'No disponible'],
['Edad al corte', String(this.age() ?? 'No disponible')],
['Estatus', this.status() || 'No disponible'],
...route.map((s, i) => ['Etapa', lines(s, i)]),
...this.history().map((h) => [
'Historial',
`${h.date} · ${h.kind} · ${h.text}${h.code && h.code !== h.text ? ' (' + h.code + ')' : ''}`,
]),
...this.tests().map((t) => [
'Pruebas',
`${t.date} · ${t.kind} · ${t.reported ?? 'Pendiente'} · ${t.results.join(' · ') || '—'}`,
]),
];
const percent = (n: number) => `${(n * 100).toFixed(2)} %`;
const scale = (model: string, horizon: string, v: ReturnType<typeof horizonRisk>) => ({
label: `${model} · ${horizon}: ${v ? percent(v.value) : 'No disponible'}`,
outcome: model,
model,
horizon,
...(v
? {
value: v.value,
...(v.low !== undefined && v.high !== undefined ? { low: v.low, high: v.high } : {}),
}
: {}),
});
const scales = this.riskScales().flatMap((r) => [
scale(r.model, 'Inmediato', r.immediate),
scale(r.model, '5 años', r.five),
]);
for (const s of scales) entries.push(['Riesgo', s.label]);
if (!scales.length)
entries.push(['Riesgo', 'Inmediato: No disponible · 5 años: No disponible']);
await downloadDocument(this.http, 'pdf', {
title: 'Ficha individual',
parameters: [
['Corte (edad, estatus y etapas)', this.cutoff()],
[
'Historial y riesgos',
'Información longitudinal disponible; no filtrada por corte histórico',
],
],
columns: ['Sección', 'Información'],
rows: entries,
timeline,
risk_scales: scales.length
? scales
: [
{ label: 'Riesgo inmediato: No disponible' },
{ label: 'Riesgo a 5 años: No disponible' },
],
});
} catch (error) {
this.exportError.set(
error instanceof Error
? `No se pudo generar la ficha PDF: ${error.message}`
: 'No se pudo generar la ficha PDF.',
);
} finally {
this.exporting.set(false);
}
}
protected readonly identity = computed(() => {
const p = this.patient();
return {
name: p?.name?.[0]?.text,
name: patientName(p),
curp: p?.identifier?.find((i) => i.system === CURP)?.value,
// each record number once (several sources may carry the same one)
numbers: [
-77
View File
@@ -1,77 +0,0 @@
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
@@ -1,48 +0,0 @@
/** 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
@@ -1,92 +0,0 @@
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',
],
]);
});
});
-87
View File
@@ -1,87 +0,0 @@
import type { Sheet } from '../export';
import type { RiskScale } from './risk-scales';
import { ANTECEDENTS } from './record-groups';
import { SOURCES, Stage, STATES } from './stages';
const NONE = 'No disponible';
const percent = (p: number) => `${(100 * p).toFixed(2)} %`;
interface Event {
date: string;
kind: string;
text: string;
}
interface Test {
date: string;
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. */
export function recordSheets(
facts: [string, string | undefined][],
stages: Stage[],
history: Event[],
tests: Test[],
forms: Form[],
scales: RiskScale[],
): Sheet[] {
return [
{
title: 'Datos de la paciente',
head: ['Dato', 'Valor'],
rows: facts.map(([k, v]) => [k, v || NONE]),
},
{
title: 'Etapas del tamizaje',
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', 'Hallazgos'],
rows: tests.map((t) => [
t.date,
t.kind,
t.reported ?? 'Pendiente',
t.results.join(' · '),
t.findings.join(' · '),
]),
},
{
title: 'Riesgos',
head: ['Riesgo', 'Probabilidad', 'IC 95 %'],
rows: scales.map(({ label, risk }) => [
label,
risk ? percent(risk.p) : NONE,
risk?.low === undefined ? NONE : `${percent(risk.low)} a ${percent(risk.high!)}`,
]),
},
];
}
-90
View File
@@ -1,90 +0,0 @@
import type { Parameters } from 'fhir/r4';
import { horizonLabel, 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: [],
});
});
});
-479
View File
@@ -1,479 +0,0 @@
import { DecimalPipe } from '@angular/common';
import { Component, 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;
}
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>
}
<div>
<dt>Desenlace</dt>
<dd>CIN3 o más grave (CIN3+)</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) {
<table class="plain" aria-label="Comparación por horizonte">
<thead>
<tr>
<th>Horizonte</th>
<th>Modelo institucional</th>
<th>Referencia NCI</th>
<th>Diferencia (puntos porcentuales)</th>
</tr>
</thead>
<tbody>
@for (h of v.horizons; track h.years) {
@for (c of h.comparisons.length ? h.comparisons : [none]; track $index) {
<tr [attr.data-years]="h.years">
<td class="nowrap" data-label="Horizonte">{{ h.label }}</td>
<td class="model" data-label="Modelo institucional">
@if (c.model) {
<strong>{{ c.title }}</strong>
<span class="muted">{{ c.outcome }}</span>
}
@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 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>
<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>
<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%;
}
th,
td {
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
.model strong,
.model .muted {
display: block;
}
.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 none: ComparisonView = {
status: 'not_comparable',
reasons: ['no_institutional_model'],
};
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
@@ -1,100 +0,0 @@
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
@@ -1,126 +0,0 @@
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('; ')}.`;
});
}
+24
View File
@@ -0,0 +1,24 @@
import type { RiskAssessment } from 'fhir/r4';
/** Only an explicitly published horizon is eligible; zero remains a real value. */
export function horizonRisk(risk: RiskAssessment, years: number) {
const p = (risk.prediction ?? []).find(
(x) =>
x.whenRange?.high?.value === years &&
x.whenRange.high.code === 'a' &&
x.probabilityDecimal !== undefined &&
x.probabilityDecimal >= 0 &&
x.probabilityDecimal <= 1,
);
if (!p) return undefined;
const value = p.probabilityDecimal!;
const get = (suffix: string) =>
p.extension?.find((e) => e.url.endsWith('/' + suffix))?.valueDecimal;
const low = get('ic-bajo'),
high = get('ic-alto');
return {
value,
low: low !== undefined && low >= 0 && low <= 1 ? low : undefined,
high: high !== undefined && high >= 0 && high <= 1 ? high : undefined,
};
}
-62
View File
@@ -1,62 +0,0 @@
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',
]);
});
});
-172
View File
@@ -1,172 +0,0 @@
import { DecimalPipe } from '@angular/common';
import { Component, input } from '@angular/core';
interface Prediction {
years: number;
p: number;
low?: number;
high?: number;
}
export interface RiskScale {
label: string;
risk?: Prediction;
}
/** 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) =>
[0, 5].map((years) => ({
label: `${m.text}, riesgo ${years ? 'a 5 años' : 'inmediato'}`,
risk: m.predictions.find((p) => p.years === years),
})),
);
}
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: `
@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>
}
}
`,
styles: `
.note {
margin: 0 0 8px;
}
.risk-scale {
margin: 8px 0 14px;
max-width: 740px;
}
.risk-scale p {
margin: 0;
}
.risk-plot {
padding-top: 24px;
position: relative;
}
.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;
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 groups = input.required<RiskGroup[]>();
}
+54
View File
@@ -0,0 +1,54 @@
import '@angular/compiler';
import { describe, expect, it } from 'vitest';
import type { RiskAssessment } from 'fhir/r4';
import { daysBetween, intervalText, stages } from './stages';
import { horizonRisk } from './risk-scale';
describe('stages and explicit risk horizons', () => {
it('keeps zero day intervals and does not fill later stages', () => {
const s = stages('2026-01-01', '2026-01-01', '2026-02-01');
expect(daysBetween(s[0].date, s[1].date)).toBe(0);
expect(s.slice(2).every((x) => x.date === undefined)).toBe(true);
expect(stages('2026-01-01', '2027-01-01', '2026-02-01')[1].date).toBeUndefined();
});
it('distinguishes inferred, structured, pending and ambiguous stages', () => {
const a = stages('2026-01-01', undefined, '2026-02-01', {
colposcopy: { state: 'inferred', date: '2026-01-03' },
biopsy: { state: 'pending' },
diagnosis: { state: 'ambiguous' },
});
expect(a.map((x) => x.state)).toEqual([
'Registrada',
'Desconocida',
'Registrada',
'Pendiente',
'Ambigua',
]);
expect(a[2].provenance).toBe('Inferida temporalmente');
expect(
stages('2026-01-01', undefined, '2026-02-01', {
biopsy: { state: 'structured', date: '2026-01-04' },
})[3].provenance,
).toBe('Vínculo estructurado');
});
it('says an interval in days, marks an inferred one, and prints a dash for a missing date', () => {
expect(intervalText('2026-01-01', '2026-01-01')).toBe('0 días');
expect(intervalText('2026-01-01', '2026-01-04', true)).toBe('3 días (inferido)');
expect(intervalText(undefined, '2026-01-04')).toBe('—');
expect(intervalText('2026-01-05', '2026-01-04')).toBe('—');
});
it('uses only a published horizon and preserves zero', () => {
const r: RiskAssessment = {
resourceType: 'RiskAssessment',
status: 'final',
subject: {},
prediction: [
{ probabilityDecimal: 0, whenRange: { high: { value: 0, code: 'a' } } },
{ probabilityDecimal: 0.2, whenRange: { high: { value: 3, code: 'a' } } },
],
};
expect(horizonRisk(r, 0)?.value).toBe(0);
expect(horizonRisk(r, 5)).toBeUndefined();
expect(horizonRisk({ ...r, prediction: [] }, 0)).toBeUndefined();
});
});
+23
View File
@@ -0,0 +1,23 @@
<div class="stage-line" [class.detailed]="detail()" [attr.aria-label]="summary()">
@for (s of rows(); track s.label) {
<div class="stage">
<span
class="node"
[class.registered]="s.state === 'Registrada'"
[class.inferred]="s.inferred"
[class.pending]="s.state === 'Pendiente'"
[class.ambiguous]="s.state === 'Ambigua'"
[attr.title]="s.title"
></span>
@if (detail()) {
<div class="stage-detail">
<strong>{{ s.label }}</strong>
<span>{{ s.state }}{{ s.provenance ? ' · ' + s.provenance : '' }}</span>
<span>{{ s.date ?? 'Sin fecha' }}</span>
<span class="interval">Desde anterior: {{ s.sincePrevious }}</span>
<span class="interval">Desde toma: {{ sinceSample(s) }}</span>
</div>
}
</div>
}
</div>
+116
View File
@@ -0,0 +1,116 @@
:host {
display: block;
min-width: 150px;
}
.stage-line {
display: flex;
align-items: flex-start;
}
.stage {
position: relative;
flex: 0 0 37px;
}
.stage:not(:last-child)::after {
content: '';
position: absolute;
top: 9px;
left: 20px;
right: 0;
border-top: 1px solid #667b8a;
}
.stage:last-child {
flex-basis: 18px;
}
.node {
display: block;
width: 18px;
height: 18px;
box-sizing: border-box;
border: 2px dashed #667b8a;
border-radius: 50%;
background: white;
position: relative;
z-index: 1;
}
.registered {
background: #387b66;
border-style: solid;
}
.inferred {
background: #4269a0;
border-style: double;
}
.pending {
background: #fff1c9;
border-style: solid;
}
.ambiguous {
border-style: double;
border-color: #a84460;
}
/* The detailed panel: one column per milestone, across the whole width. */
.detailed {
background: #fff;
border: 1px solid #dce3e7;
border-radius: 8px;
padding: 18px 12px;
}
.detailed .stage,
.detailed .stage:last-child {
flex: 1;
min-width: 0;
text-align: center;
}
.detailed .node {
margin: 0 auto;
}
.detailed .stage:not(:last-child)::after {
left: calc(50% + 9px);
right: calc(-50% + 9px);
}
.stage-detail {
display: flex;
flex-direction: column;
gap: 3px;
padding: 8px 4px 0;
font-size: 12px;
color: #60717d;
overflow-wrap: anywhere;
}
.stage-detail strong {
color: #243d4b;
}
.interval {
font-weight: 600;
color: #365b69;
}
@media (max-width: 700px) {
.node {
flex: none;
}
.detailed {
display: block;
}
.detailed .stage {
display: flex;
gap: 12px;
padding-bottom: 10px;
text-align: left;
}
.detailed .stage::after {
top: 18px;
left: 9px;
bottom: 0;
right: auto;
border-top: 0;
border-left: 1px solid #667b8a;
}
.detailed .node {
margin: 0;
}
.stage-detail {
padding: 0;
}
}
-126
View File
@@ -1,126 +0,0 @@
import { EXT } from '../fhir';
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 });
describe('the route of a cytology', () => {
it('says what is recorded, inferred, pending and unknown, by the cut-off', () => {
const report = cytology(
ext('colposcopy-date', { valueDate: '2026-02-01' }),
ext('biopsy-request-date', { valueDate: '2026-02-01' }),
ext('biopsy-date', { valueDate: '2026-03-01' }),
ext('biopsy-link', { valueCode: 'recorded' }),
);
const states = (cutoff: string) => route(report, cutoff).map((s) => s.state);
expect(states('2026-12-31')).toEqual([
'recorded',
'unknown',
'inferred',
'recorded',
'unknown',
]);
expect(states('2026-02-15')[3]).toBe('pending');
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('—');
});
});
+103 -243
View File
@@ -1,267 +1,127 @@
import { Component, computed, input } from '@angular/core';
import type { DiagnosticReport } from 'fhir/r4';
import { EXT, ext } from '../fhir';
import { ext } from '../fhir';
/** 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' | '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;
export type StageFact = { state?: string; date?: string };
export type StageFacts = Record<string, StageFact>;
export function routeFacts(report?: DiagnosticReport): StageFacts {
return Object.fromEntries(
['colposcopy', 'biopsy', 'diagnosis'].map((k) => [
k,
{
state: ext(report, `stage-${k}-state`)?.valueCode,
date: ext(report, `stage-${k}-date`)?.valueDate,
},
]),
);
}
/** 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 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 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 };
export function stages(sample?: string, report?: string, cutoff?: string, facts: StageFacts = {}) {
const valid = (d?: string) => !!d && !!cutoff && /^\d{4}-\d{2}-\d{2}$/.test(d) && d <= cutoff;
const start = valid(sample) ? sample : undefined;
const result = start && valid(report) && report! >= start ? report : undefined;
const later = (label: string, key: string) => {
const f = facts[key];
const state =
f?.state === 'pending'
? 'Pendiente'
: f?.state === 'ambiguous'
? 'Ambigua'
: (f?.state === 'inferred' || f?.state === 'structured') &&
valid(f.date) &&
start &&
f.date! >= start
? 'Registrada'
: 'Desconocida';
return {
label,
date: state === 'Registrada' ? f.date : undefined,
state,
provenance:
state === 'Registrada'
? f.state === 'inferred'
? 'Inferida temporalmente'
: 'Vínculo estructurado'
: undefined,
};
};
const day = (label: string, d: string | undefined, sources: string[]): Stage => ({
label,
day: d,
state: d ? 'recorded' : 'unknown',
sources: d ? sources : undefined,
});
const linked = ext(cytology, 'biopsy-link')?.valueCode === 'recorded' ? 'recorded' : 'inferred';
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 [
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,
later('Diagnóstico', 'diagnosis', at('diagnosis-date'), 'inferred'),
{
label: 'Toma de muestra',
date: start,
state: start ? 'Registrada' : 'Desconocida',
provenance: undefined,
},
{
label: 'Resultado de citología',
date: result,
state: result ? 'Registrada' : 'Desconocida',
provenance: undefined,
},
later('Colposcopia', 'colposcopy'),
later('Reporte de biopsia', 'biopsy'),
later('Diagnóstico', 'diagnosis'),
];
}
/** Whole days between two days; none when either is missing or they are out of order. */
export function between(from?: string, to?: string): number | undefined {
if (!from || !to || to < from) return undefined;
return Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);
export function daysBetween(a?: string, b?: string): number | undefined {
if (!a || !b) return undefined;
const x = Date.parse(a + 'T00:00:00Z'),
y = Date.parse(b + 'T00:00:00Z');
return Number.isFinite(x) && Number.isFinite(y) && y >= x ? (y - x) / 86400000 : undefined;
}
/** One stage as the screens say it, with the intervals the detailed panel prints. */
export interface StageRow {
label: string;
state: string;
provenance?: string;
date?: string;
inferred: boolean;
title: string;
/** "3 días", "3 días (inferido)" or "—": never a zero for a missing date */
sincePrevious: string;
}
/** 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)' : ''}`;
/** Days between two stages as text; an interval that rests on an inferred stage says so. */
export function intervalText(from?: string, to?: string, inferred = false): string {
const days = daysBetween(from, to);
return days === undefined ? '—' : `${days} 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()" [attr.aria-label]="summary()">
@for (s of shown(); track s.label) {
<li [title]="s.title">
<span class="node" [class]="s.state"></span>
@if (detail()) {
<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;
list-style: none;
margin: 0;
padding: 0;
}
li {
position: relative;
}
/* 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%;
box-sizing: border-box;
display: block;
height: 12px;
position: relative;
width: 12px;
z-index: 1;
}
.recorded {
background: #387b66;
border-style: solid;
}
.inferred {
background: #4269a0;
border-style: double;
}
.pending {
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;
}
}
`,
templateUrl: './stages.html',
styleUrl: './stages.scss',
})
export class Stages {
readonly stages = input.required<Stage[]>();
/** the cytology's sample day, its report day, and the day the route is known by */
readonly sample = input<string>();
readonly report = input<string>();
readonly cutoff = input<string>();
/** the detailed panel (milestones, states, dates, intervals) instead of the compact line */
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) => ({
readonly facts = input<StageFacts>({});
protected readonly items = computed(() =>
stages(this.sample(), this.report(), this.cutoff(), this.facts()),
);
protected readonly rows = computed<StageRow[]>(() => {
const items = this.items();
const inferred = (x?: { provenance?: string }) => x?.provenance === 'Inferida temporalmente';
return items.map((s, i) => ({
...s,
text: STATES[s.state],
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)),
inferred: inferred(s),
title: `${s.label}: ${s.state}${s.provenance ? ' · ' + s.provenance : ''}`,
sincePrevious: intervalText(
i ? items[i - 1].date : undefined,
s.date,
inferred(s) || (i > 0 && inferred(items[i - 1])),
),
}));
});
protected readonly summary = computed(() =>
this.shown()
.map((s) => s.title)
this.rows()
.map((r) => r.title)
.join('; '),
);
protected sinceSample(row: StageRow): string {
return intervalText(this.items()[0].date, row.date, row.inferred);
}
}