Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 24415b79b6 | |||
| b43c89befd | |||
| 9c17a383d1 | |||
| 8e16de33b7 | |||
| 5d660b7043 | |||
| a3a100450b | |||
| a92515eb4d | |||
| 5f92c49ed4 | |||
| a22ce12067 | |||
| a19874438b | |||
| c08a0b8874 | |||
| 5201340a13 | |||
| cca9517b7c | |||
| 3693991772 | |||
| e49dde10e7 | |||
| 2dec5af826 | |||
| 0316966374 | |||
| 3d72c153c5 | |||
| 422b408e37 | |||
| 211f02edad | |||
| 32b879edd2 | |||
| 9726d6faa3 | |||
| bafd6760d4 | |||
| 0666ce3077 | |||
| d2eada9385 | |||
| 0d458818b5 | |||
| 2970ce16b0 | |||
| a43cf4b51b | |||
| a4cc80fbe2 | |||
| 370da43695 | |||
| f7fdab950a | |||
| 1260e0ff2a |
+7
-7
@@ -14,8 +14,8 @@ const TITLES = {
|
|||||||
cytology: 'Distribución de resultados citológicos',
|
cytology: 'Distribución de resultados citológicos',
|
||||||
genotype: 'Resultados de VPH por genotipo',
|
genotype: 'Resultados de VPH por genotipo',
|
||||||
biopsy: 'Resultados de biopsia cervical',
|
biopsy: 'Resultados de biopsia cervical',
|
||||||
colposcopy: 'Valor predictivo positivo de la colposcopía',
|
colposcopy: 'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||||
ppvBiopsy: 'Valor predictivo positivo de la biopsia',
|
ppvBiopsy: 'Tasa de confirmación histopatológica de referencia a biopsia',
|
||||||
};
|
};
|
||||||
|
|
||||||
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
|
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
|
||||||
@@ -30,17 +30,17 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
|
|||||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||||
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
|
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
|
||||||
'Indicadores de oportunidad',
|
'Indicadores de oportunidad',
|
||||||
'Tiempos de la ruta del tamizaje',
|
'Días de la ruta del tamizaje',
|
||||||
'Indicadores clínicos',
|
'Indicadores clínicos',
|
||||||
'Resultados de citología, VPH y biopsia',
|
'Resultados de citología, VPH y biopsia',
|
||||||
'Distribución de resultados citológicos',
|
'Distribución de resultados citológicos',
|
||||||
'Resultados de VPH por genotipo',
|
'Resultados de VPH por genotipo',
|
||||||
'Resultados de biopsia cervical',
|
'Resultados de biopsia cervical',
|
||||||
'Tasa de confirmación histopatológica',
|
'Tasa de confirmación histopatológica',
|
||||||
'Valor predictivo positivo de la colposcopía',
|
'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||||
]);
|
]);
|
||||||
const route = tab.locator('app-readings').first();
|
const route = tab.locator('app-readings').first();
|
||||||
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
|
for (const mode of ['Por pasos', 'Primer diagnóstico', 'Diagnóstico tras biopsia', 'Acumulado desde la toma']) {
|
||||||
await route.getByRole('radio', { name: mode }).click();
|
await route.getByRole('radio', { name: mode }).click();
|
||||||
await expect(
|
await expect(
|
||||||
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
|
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
|
||||||
@@ -105,14 +105,14 @@ test('indicadores cacu: its sections in order, each card read one mode at a time
|
|||||||
.getByRole('radio', ROUND)
|
.getByRole('radio', ROUND)
|
||||||
.click();
|
.click();
|
||||||
await expect(
|
await expect(
|
||||||
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
|
tab.getByRole('heading', { name: 'Tasa de confirmación histopatológica de referencia a biopsia' }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
|
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
|
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
|
||||||
await page.goto('/indicadores/cacu');
|
await page.goto('/indicadores/cacu');
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
const list = page.locator('table.worklist tbody tr');
|
const list = page.locator('table.worklist tbody tr');
|
||||||
await expect(list.first().locator('app-stages li')).toHaveCount(5);
|
await expect(list.first().locator('app-stages li')).toHaveCount(5);
|
||||||
await list.first().getByRole('button', { name: 'Detalle' }).click();
|
await list.first().getByRole('button', { name: 'Detalle' }).click();
|
||||||
|
|||||||
+345
-13
@@ -14,7 +14,7 @@ test.beforeEach(async ({ page }) => {
|
|||||||
/** The record of the first patient of the risk list, as an address. */
|
/** The record of the first patient of the risk list, as an address. */
|
||||||
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
|
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
|
||||||
await page.goto('/indicadores/cacu');
|
await page.goto('/indicadores/cacu');
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
const link = page.locator('table.worklist tbody tr a').first();
|
const link = page.locator('table.worklist tbody tr a').first();
|
||||||
await link.waitFor({ timeout: 120_000 });
|
await link.waitFor({ timeout: 120_000 });
|
||||||
const url = (await link.getAttribute('href'))!;
|
const url = (await link.getAttribute('href'))!;
|
||||||
@@ -118,17 +118,18 @@ async function open(page: Page, url: string) {
|
|||||||
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
|
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
test('ficha (simulado): states why a hysterectomy makes this risk assessment unavailable', async ({
|
test('ficha (simulado): uses the recorded hysterectomy when eligibility is unavailable', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const { url, sample } = await firstRecord(page);
|
const { url, sample } = await firstRecord(page);
|
||||||
const previousDay = plus(sample, -1);
|
const previousDay = plus(sample, -1);
|
||||||
|
await eligibilityIs(page, {}, 503);
|
||||||
await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
|
await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
|
||||||
const response = await route.fetch();
|
const response = await route.fetch();
|
||||||
const patient = await response.json();
|
const patient = await response.json();
|
||||||
patient.extension = [
|
patient.extension = [
|
||||||
...(patient.extension ?? []),
|
...(patient.extension ?? []),
|
||||||
{ url: EXT + 'first-hysterectomy-recorded', valueDate: sample },
|
{ url: EXT + 'first-hysterectomy-recorded', valueDate: sample.slice(0, 10) },
|
||||||
];
|
];
|
||||||
await route.fulfill({ response, json: patient });
|
await route.fulfill({ response, json: patient });
|
||||||
});
|
});
|
||||||
@@ -136,7 +137,7 @@ test('ficha (simulado): states why a hysterectomy makes this risk assessment una
|
|||||||
|
|
||||||
await open(page, url);
|
await open(page, url);
|
||||||
await expect(
|
await expect(
|
||||||
page.getByText('Sin estimación de riesgo por antecedente de histerectomía', {
|
page.getByText('No disponible por: histerectomía registrada el', {
|
||||||
exact: false,
|
exact: false,
|
||||||
}),
|
}),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
@@ -1015,8 +1016,8 @@ test('curvas (simulado): one series per model at its published horizons, its ban
|
|||||||
// ---- the grouped NCI comparison, the survival texts and the risk-model selection (all "simulado") ------
|
// ---- the grouped NCI comparison, the survival texts and the risk-model selection (all "simulado") ------
|
||||||
|
|
||||||
const SHOTS = process.env['SHOTS_DIR']; // when set, the simulated pages are saved for the report
|
const SHOTS = process.env['SHOTS_DIR']; // when set, the simulated pages are saved for the report
|
||||||
const shot = async (page: Page, name: string) => {
|
const shot = async (page: Page, name: string, kind = 'SIMULADO') => {
|
||||||
if (SHOTS) await page.screenshot({ path: `${SHOTS}/SIMULADO-${name}.png`, fullPage: true });
|
if (SHOTS) await page.screenshot({ path: `${SHOTS}/${kind}-${name}.png`, fullPage: true });
|
||||||
};
|
};
|
||||||
const institutional = (p: number, low?: number, high?: number, diff?: number) => [
|
const institutional = (p: number, low?: number, high?: number, diff?: number) => [
|
||||||
part('institutional', { valueDecimal: p }),
|
part('institutional', { valueDecimal: p }),
|
||||||
@@ -1244,13 +1245,16 @@ const scenarioReport = (name: string, n: number, deaths: number) => ({
|
|||||||
weibull_fractional: { t: [0, 12, 36, 60], S: [1, 0.91, 0.79, 0.71] },
|
weibull_fractional: { t: [0, 12, 36, 60], S: [1, 0.91, 0.79, 0.71] },
|
||||||
points: { COMB: { S: [0.92, 0.8, 0.7], low: [0.85, 0.7, 0.55], high: [0.97, 0.9, 0.82] } },
|
points: { COMB: { S: [0.92, 0.8, 0.7], low: [0.85, 0.7, 0.55], high: [0.97, 0.9, 0.82] } },
|
||||||
});
|
});
|
||||||
async function withSurvival(page: Page, domain: 'cacu' | 'cama', others: object[] = []) {
|
async function withSurvival(
|
||||||
|
page: Page,
|
||||||
|
domain: 'cacu' | 'cama',
|
||||||
|
others: object[] = [],
|
||||||
|
report?: object,
|
||||||
|
scenarios = ['Edad al diagnóstico · 45-54 años', 'VPH positivo'],
|
||||||
|
) {
|
||||||
const assessed = {
|
const assessed = {
|
||||||
...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]),
|
...risk('s', 'Supervivencia v3', `${domain}.survival`, '2026-02-01', [[5, 0.7, 0.55, 0.82]]),
|
||||||
extension: [
|
extension: scenarios.map((valueString) => ({ url: EXT + 'escenario-clinico', valueString })),
|
||||||
{ url: EXT + 'escenario-clinico', valueString: 'Edad al diagnóstico · 45-54 años' },
|
|
||||||
{ url: EXT + 'escenario-clinico', valueString: 'VPH positivo' },
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) =>
|
await page.route(`**/api/${domain}/fhir/RiskAssessment**`, (route) =>
|
||||||
route.fulfill({
|
route.fulfill({
|
||||||
@@ -1267,13 +1271,15 @@ async function withSurvival(page: Page, domain: 'cacu' | 'cama', others: object[
|
|||||||
(route) =>
|
(route) =>
|
||||||
route.fulfill({
|
route.fulfill({
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(
|
||||||
|
report ?? {
|
||||||
escenarios: [
|
escenarios: [
|
||||||
scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6),
|
scenarioReport('Edad al diagnóstico · 45-54 años', 12, 6),
|
||||||
scenarioReport('VPH positivo', 30, 9),
|
scenarioReport('VPH positivo', 30, 9),
|
||||||
],
|
],
|
||||||
factores_escenarios: [],
|
factores_escenarios: [],
|
||||||
}),
|
},
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1385,3 +1391,329 @@ test('escalas (simulado): with a survival model and compatible risk models, only
|
|||||||
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
|
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
|
||||||
await shot(page, 'escalas-supervivencia-y-riesgo-1440');
|
await shot(page, 'escalas-supervivencia-y-riesgo-1440');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---- Eligibility decisions in "Riesgos y recomendaciones" ----
|
||||||
|
|
||||||
|
const ELIGIBILITY = '**/api/cacu/fhir/Patient/*/$eligibility*';
|
||||||
|
const SCENARIO_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
|
||||||
|
const CRITERION_SYSTEM = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
|
||||||
|
const riskBox = (page: Page) =>
|
||||||
|
page.locator('mat-card', {
|
||||||
|
has: page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
|
||||||
|
});
|
||||||
|
const visit = (scenario: string, date: string, eligible: boolean, criteria: string[] = []) =>
|
||||||
|
part('candidate', {
|
||||||
|
part: [
|
||||||
|
part('scenario', { valueCoding: { system: SCENARIO_SYSTEM, code: scenario } }),
|
||||||
|
part('index-date', { valueDate: date }),
|
||||||
|
part('eligible', { valueBoolean: eligible }),
|
||||||
|
...criteria.map((code) =>
|
||||||
|
part('criterion', { valueCoding: { system: CRITERION_SYSTEM, code } }),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const eligibilityAnswer = (status: string, ...candidates: object[]) =>
|
||||||
|
answerOf(part('status', { valueCode: status }), ...candidates);
|
||||||
|
const eligibilityIs = (page: Page, body: object, status = 200) =>
|
||||||
|
page.route(ELIGIBILITY, (route) =>
|
||||||
|
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }),
|
||||||
|
);
|
||||||
|
|
||||||
|
async function withFollowUp(page: Page, status: string, recorded?: string) {
|
||||||
|
await page.route('**/api/cacu/fhir/Patient/*', async (route) => {
|
||||||
|
const response = await route.fetch();
|
||||||
|
const patient = await response.json();
|
||||||
|
patient.extension = (patient.extension ?? []).filter(
|
||||||
|
(e: { url: string }) =>
|
||||||
|
e.url !== EXT + 'follow-up-status' && e.url !== EXT + 'first-hysterectomy-recorded',
|
||||||
|
);
|
||||||
|
patient.extension.push({ url: EXT + 'follow-up-status', valueCoding: { code: status } });
|
||||||
|
if (recorded) {
|
||||||
|
patient.extension.push({ url: EXT + 'first-hysterectomy-recorded', valueDate: recorded });
|
||||||
|
}
|
||||||
|
await route.fulfill({ response, json: patient });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('elegibilidad: the risk section shows the published post-treatment exclusion', async ({ page }) => {
|
||||||
|
const patients = await page.request.get(
|
||||||
|
'/api/cacu/fhir/Patient?_count=200&follow-up-status=post_treatment',
|
||||||
|
);
|
||||||
|
expect(patients.ok()).toBe(true);
|
||||||
|
const { entry } = await patients.json();
|
||||||
|
const code = 'no_pretreatment_biopsy';
|
||||||
|
let patientId: string | undefined;
|
||||||
|
for (const { resource } of entry ?? []) {
|
||||||
|
const response = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$eligibility`);
|
||||||
|
expect(response.ok()).toBe(true);
|
||||||
|
const { parameter } = await response.json();
|
||||||
|
const latest = parameter
|
||||||
|
.filter((p: any) =>
|
||||||
|
p.name === 'candidate' && p.part.some((v: any) =>
|
||||||
|
v.name === 'scenario' && v.valueCoding.code === 'post_treatment',
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.map((p: any) => ({
|
||||||
|
day: p.part.find((v: any) => v.name === 'index-date').valueDate as string,
|
||||||
|
eligible: p.part.find((v: any) => v.name === 'eligible').valueBoolean as boolean,
|
||||||
|
criteria: p.part.filter((v: any) => v.name === 'criterion').map((v: any) => v.valueCoding.code),
|
||||||
|
}))
|
||||||
|
.sort((a: { day: string }, b: { day: string }) => b.day.localeCompare(a.day))[0];
|
||||||
|
if (latest && !latest.eligible && latest.criteria.length === 1 && latest.criteria[0] === code) {
|
||||||
|
patientId = resource.id;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(patientId, 'a synthetic patient with a published post-treatment exclusion').toBeDefined();
|
||||||
|
await open(page, `/indicadores/cacu/pacientes/${patientId}`);
|
||||||
|
const box = riskBox(page);
|
||||||
|
await expect(box.getByRole('status')).toHaveText(
|
||||||
|
'No disponible por: Sin biopsia previa al tratamiento en el periodo requerido.',
|
||||||
|
);
|
||||||
|
await expect(box.locator('app-risk-scales')).toHaveCount(0);
|
||||||
|
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const width of [1440, 480]) {
|
||||||
|
test('elegibilidad (simulado) at ' + width + ' px: the risk section shows all reasons from the selected visit', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize({ width, height: 1000 });
|
||||||
|
const { url, sample } = await firstRecord(page);
|
||||||
|
const day = sample.slice(0, 10);
|
||||||
|
await withFollowUp(page, 'pre_colposcopy');
|
||||||
|
await eligibilityIs(
|
||||||
|
page,
|
||||||
|
eligibilityAnswer(
|
||||||
|
'evaluated',
|
||||||
|
visit('pre_colposcopy', plus(day, 1), true),
|
||||||
|
visit('pre_colposcopy', plus(day, -3), false, ['regla_anterior']),
|
||||||
|
visit('pre_colposcopy', plus(day, -2), false, ['no_index_result', 'regla_nueva']),
|
||||||
|
visit('surveillance', day, false, ['cancer_history']),
|
||||||
|
visit('post_colposcopy', day, false, ['prior_treatment']),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await open(page, url);
|
||||||
|
const box = riskBox(page);
|
||||||
|
await expect(box.getByRole('status')).toHaveText(
|
||||||
|
'No disponible por: Sin resultado de citología o VPH en la visita índice; regla_nueva.',
|
||||||
|
);
|
||||||
|
await expect(box.locator('app-risk-scales')).toHaveCount(0);
|
||||||
|
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
|
||||||
|
expect(await layoutProblems(page)).toEqual([]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('elegibilidad (simulado): precolposcopy falls back to surveillance when it has no visit by the index', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const { url, sample } = await firstRecord(page);
|
||||||
|
const day = sample.slice(0, 10);
|
||||||
|
await withFollowUp(page, 'pre_colposcopy');
|
||||||
|
await eligibilityIs(
|
||||||
|
page,
|
||||||
|
eligibilityAnswer(
|
||||||
|
'evaluated',
|
||||||
|
visit('pre_colposcopy', plus(day, 1), true),
|
||||||
|
visit('surveillance', day, false, ['prior_outcome']),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await open(page, url);
|
||||||
|
await expect(riskBox(page).getByRole('status')).toHaveText(
|
||||||
|
'No disponible por: Resultado CIN2+ previo al índice.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const status of ['evaluated', 'no_candidate']) {
|
||||||
|
test('elegibilidad (simulado): ' + status + ' takes precedence over recorded hysterectomy', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const { url, sample } = await firstRecord(page);
|
||||||
|
const day = sample.slice(0, 10);
|
||||||
|
await withFollowUp(page, 'pre_colposcopy', day);
|
||||||
|
await eligibilityIs(
|
||||||
|
page,
|
||||||
|
status === 'evaluated'
|
||||||
|
? eligibilityAnswer(
|
||||||
|
status,
|
||||||
|
visit('pre_colposcopy', day, true),
|
||||||
|
visit('surveillance', day, false, ['hysterectomy']),
|
||||||
|
)
|
||||||
|
: eligibilityAnswer(status),
|
||||||
|
);
|
||||||
|
const answer = page.waitForResponse((r) => r.url().includes('/$eligibility'));
|
||||||
|
await open(page, url);
|
||||||
|
await answer;
|
||||||
|
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
|
||||||
|
await expect(riskBox(page).getByText('No disponible por:', { exact: false })).toHaveCount(0);
|
||||||
|
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('elegibilidad (simulado): a new patient never inherits the previous risk exclusion', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await firstRecord(page);
|
||||||
|
const links = page.locator('table.worklist tbody tr a');
|
||||||
|
const records = await links.evaluateAll((els) => {
|
||||||
|
const unique = new Map<string, string>();
|
||||||
|
for (const el of els) {
|
||||||
|
const href = el.getAttribute('href')!;
|
||||||
|
const id = /pacientes\/([^?]+)/.exec(href)![1];
|
||||||
|
if (!unique.has(id)) unique.set(id, href);
|
||||||
|
if (unique.size === 2) break;
|
||||||
|
}
|
||||||
|
return [...unique];
|
||||||
|
});
|
||||||
|
expect(records).toHaveLength(2);
|
||||||
|
const [[firstId, firstUrl], [secondId]] = records;
|
||||||
|
await withFollowUp(page, 'pre_colposcopy');
|
||||||
|
let release!: () => void;
|
||||||
|
const gate = new Promise<void>((resolve) => (release = resolve));
|
||||||
|
await page.route(ELIGIBILITY, async (route) => {
|
||||||
|
const first = new URL(route.request().url()).pathname.endsWith(`/${firstId}/$eligibility`);
|
||||||
|
if (!first) await gate;
|
||||||
|
await route.fulfill({
|
||||||
|
contentType: 'application/fhir+json',
|
||||||
|
json: eligibilityAnswer(
|
||||||
|
'evaluated',
|
||||||
|
visit('pre_colposcopy', '1900-01-01', !first, first ? ['prior_outcome'] : []),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const reason = riskBox(page).getByText('No disponible por: Resultado CIN2+ previo al índice.');
|
||||||
|
try {
|
||||||
|
await open(page, firstUrl);
|
||||||
|
await expect(reason).toBeVisible();
|
||||||
|
await page.getByRole('link', { name: 'Regresar' }).click();
|
||||||
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
|
await page.locator(`a[href*="/pacientes/${secondId}?"]`).first().click();
|
||||||
|
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
|
||||||
|
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
|
||||||
|
await expect(reason).toHaveCount(0);
|
||||||
|
const answer = page.waitForResponse((r) => r.url().includes(`/${secondId}/$eligibility`));
|
||||||
|
release();
|
||||||
|
await answer;
|
||||||
|
await expect(riskBox(page).locator('app-risk-scales')).toBeVisible();
|
||||||
|
await expect(reason).toHaveCount(0);
|
||||||
|
} finally {
|
||||||
|
release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('elegibilidad: CaMa has no such section and never asks for it', async ({ page }) => {
|
||||||
|
let asked = false;
|
||||||
|
await page.route('**/$eligibility*', (route) => {
|
||||||
|
asked = true;
|
||||||
|
return route.abort();
|
||||||
|
});
|
||||||
|
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
|
||||||
|
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
|
||||||
|
await expect(page.locator('app-paciente')).toBeVisible({ timeout: 120_000 });
|
||||||
|
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
|
||||||
|
await expect(page.locator('[data-section=elegibilidad]')).toHaveCount(0);
|
||||||
|
expect(asked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- survival curves: absent values, insufficient data and absent scenarios (all "simulado") ----
|
||||||
|
|
||||||
|
const A = 'Edad al diagnóstico · 45-54 años';
|
||||||
|
const B = 'VPH negativo';
|
||||||
|
const C = 'Citología · LIEAG';
|
||||||
|
const partial = scenarioReport(A, 12, 6);
|
||||||
|
partial.km = {
|
||||||
|
months: [0, 12, 24, 36],
|
||||||
|
S: [1, 0.9, 0.8, 0.7],
|
||||||
|
low: [1, 0.8, null, 0.55],
|
||||||
|
high: [1, 0.95, null, 0.82],
|
||||||
|
} as any;
|
||||||
|
partial.points = {
|
||||||
|
COMB: { S: [0, null, 0.7], low: [null, null, 0.55], high: [null, null, 0.82] },
|
||||||
|
} as any;
|
||||||
|
const contract = {
|
||||||
|
escenarios: [partial],
|
||||||
|
escenarios_sin_curvas: [{ escenario: B, n: 9, fallecidos: 2 }],
|
||||||
|
min_fallecidos_escenario: 5,
|
||||||
|
factores_escenarios: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const width of [1440, 480]) {
|
||||||
|
test(`supervivencia (simulado) at ${width} px: absent limits draw no band, zero is not unavailable, insufficient data is told apart from an absent scenario`, async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await page.setViewportSize({ width, height: 1000 });
|
||||||
|
const { url } = await firstRecord(page);
|
||||||
|
await withSurvival(page, 'cacu', [], contract, [A, B, C]);
|
||||||
|
await open(page, url);
|
||||||
|
const card = page.locator('[data-section=supervivencia]');
|
||||||
|
await expect(card.locator('[data-note=grupo]')).toContainText(
|
||||||
|
'no son predicciones individuales',
|
||||||
|
);
|
||||||
|
const plot = await card
|
||||||
|
.locator('.js-plotly-plot')
|
||||||
|
.first()
|
||||||
|
.evaluate((e: any) => ({
|
||||||
|
bands: e.data.filter((t: any) => t.fill === 'toself').map((t: any) => t.y),
|
||||||
|
model: e.data.find((t: any) => t.name?.startsWith('LR + HBN')),
|
||||||
|
km: e.data.find((t: any) => t.name?.startsWith('Kaplan')),
|
||||||
|
}));
|
||||||
|
expect(plot.bands.length).toBe(1); // only where both limits exist (the first two points)
|
||||||
|
expect(plot.bands[0].every((v: unknown) => typeof v === 'number')).toBe(true);
|
||||||
|
expect(plot.km.y).toEqual([1, 0.9, 0.8, 0.7]); // the curve itself stays whole
|
||||||
|
expect(plot.model.y).toEqual([0, null, 0.7]); // a real zero is drawn; the unavailable value is a gap
|
||||||
|
expect(plot.model.error_y.array).toEqual([null, null, expect.closeTo(0.12, 5)]); // no bar from absent limits
|
||||||
|
const insufficient = card.locator('[data-state=insuficiente]');
|
||||||
|
await expect(insufficient).toHaveCount(1);
|
||||||
|
await expect(insufficient).toContainText('Datos insuficientes para trazar la curva');
|
||||||
|
await expect(insufficient).toContainText('n = 9, fallecidos = 2');
|
||||||
|
await expect(insufficient).toContainText('mínimo requerido: 5 fallecidos');
|
||||||
|
const absent = card.locator('[data-state=sin-informacion]');
|
||||||
|
await expect(absent).toHaveCount(1);
|
||||||
|
await expect(absent).toContainText(
|
||||||
|
'Sin información de este escenario en el informe del modelo',
|
||||||
|
);
|
||||||
|
await expect(absent).not.toContainText('insuficientes');
|
||||||
|
await expect(card.locator('h4', { hasText: C })).toHaveCount(1);
|
||||||
|
await expect(card.locator('h4', { hasText: B })).toHaveCount(1);
|
||||||
|
expect(
|
||||||
|
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
|
||||||
|
).toBe(true);
|
||||||
|
await shot(page, `supervivencia-valores-ausentes-${width}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('supervivencia (simulado): CaCu distinguishes an unlisted scenario from having no applicable report', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const { url } = await firstRecord(page);
|
||||||
|
await withSurvival(page, 'cacu', [], { escenarios: [], factores_escenarios: [] }, [A]);
|
||||||
|
await open(page, url);
|
||||||
|
const card = page.locator('[data-section=supervivencia]');
|
||||||
|
await expect(card.locator('[data-state=sin-informacion]')).toHaveCount(1);
|
||||||
|
await expect(card.locator('[data-state=insuficiente]')).toHaveCount(0);
|
||||||
|
await expect(card).not.toContainText('datos insuficientes');
|
||||||
|
|
||||||
|
await page.unroute('**/api/cacu/fhir/RiskAssessment**');
|
||||||
|
await withSurvival(page, 'cacu', [], undefined, []);
|
||||||
|
await open(page, url);
|
||||||
|
await expect(card.locator('[data-state=sin-informe]')).toHaveText(
|
||||||
|
'No disponible: no hay un informe de supervivencia para los escenarios de la paciente.',
|
||||||
|
);
|
||||||
|
await expect(card.locator('[data-state=insuficiente]')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('supervivencia (simulado): CaMa keeps its own wording for a scenario without a curve', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
const patients = await (await page.request.get('/api/cama/fhir/Patient?_count=1')).json();
|
||||||
|
await withSurvival(page, 'cama', [], contract, [A, B]);
|
||||||
|
await page.goto(`/indicadores/cama/pacientes/${patients.entry[0].resource.id}`);
|
||||||
|
const card = page.locator('[data-section=supervivencia]');
|
||||||
|
await expect(card).toBeVisible({ timeout: 120_000 });
|
||||||
|
await expect(card.locator('mat-card-title')).toHaveText('Riesgo de muerte');
|
||||||
|
await expect(card).toContainText('No disponible: datos insuficientes.');
|
||||||
|
await expect(card.locator('[data-state=insuficiente], [data-state=sin-informacion]')).toHaveCount(
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|||||||
+16
-6
@@ -58,14 +58,14 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
|||||||
);
|
);
|
||||||
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
|
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
|
||||||
|
|
||||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
await page.getByRole('tab', { name: 'Histórico' }).click();
|
||||||
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
|
await expect(page.locator('app-tab-trazabilidad section.panel')).toHaveCount(9);
|
||||||
|
|
||||||
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
|
||||||
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
|
await expect(page.locator('app-tab-definiciones details')).toHaveCount(21);
|
||||||
|
|
||||||
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
|
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
const bundle = await (await list).json();
|
const bundle = await (await list).json();
|
||||||
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
|
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
|
||||||
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
|
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
|
||||||
@@ -84,8 +84,8 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
|
|||||||
).not.toContainText('Sin estudios');
|
).not.toContainText('Sin estudios');
|
||||||
|
|
||||||
await page.goto('/indicadores/cama');
|
await page.goto('/indicadores/cama');
|
||||||
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
|
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
|
||||||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
await page.getByRole('tab', { name: 'Seguimiento' }).click();
|
||||||
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
|
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
|
||||||
await page.getByRole('option', { name: '12 meses' }).click();
|
await page.getByRole('option', { name: '12 meses' }).click();
|
||||||
const camaRows = page.locator('table.worklist tbody tr');
|
const camaRows = page.locator('table.worklist tbody tr');
|
||||||
@@ -205,6 +205,16 @@ function captured(domain: string) {
|
|||||||
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
|
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
|
||||||
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
|
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
|
||||||
|
|
||||||
|
for (const domain of ['cacu', 'cama', 'tea']) {
|
||||||
|
test(`pestañas de indicadores ${domain} tienen nombres únicos`, async ({ page }) => {
|
||||||
|
await page.goto(`/indicadores/${domain}`);
|
||||||
|
await expect(page.getByRole('tab', { name: 'Seguimiento', exact: true })).toHaveCount(1);
|
||||||
|
await expect(page.getByRole('tab', { name: 'Histórico', exact: true })).toHaveCount(1);
|
||||||
|
const labels = await page.getByRole('tab').allTextContents();
|
||||||
|
expect(new Set(labels.map((s) => s.trim())).size).toBe(labels.length);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
|
// CaCu's page is its own (Phase 6); CaMa's and TEA's follow the old one.
|
||||||
for (const domain of ['cama', 'tea']) {
|
for (const domain of ['cama', 'tea']) {
|
||||||
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
|
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
|
||||||
@@ -242,7 +252,7 @@ for (const domain of ['cama', 'tea']) {
|
|||||||
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
|
||||||
const from = headings.indexOf('Indicadores de oportunidad');
|
const from = headings.indexOf('Indicadores de oportunidad');
|
||||||
expect(headings.slice(from).map(period)).toEqual(
|
expect(headings.slice(from).map(period)).toEqual(
|
||||||
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
|
old.filter((i) => i.kind !== 'plot').map((i) => period(domain === 'cama' ? i.text.replace(/^Tiempo de /, 'Días de ') : i.text)),
|
||||||
);
|
);
|
||||||
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
|
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
|
||||||
const drawn = await tab
|
const drawn = await tab
|
||||||
@@ -268,7 +278,7 @@ for (const domain of ['cacu', 'cama', 'tea']) {
|
|||||||
['h2', 'h3', 'plot'].includes(i.kind),
|
['h2', 'h3', 'plot'].includes(i.kind),
|
||||||
);
|
);
|
||||||
await page.goto(`/indicadores/${domain}`);
|
await page.goto(`/indicadores/${domain}`);
|
||||||
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
|
await page.getByRole('tab', { name: 'Histórico' }).click();
|
||||||
const tab = page.locator('app-tab-trazabilidad');
|
const tab = page.locator('app-tab-trazabilidad');
|
||||||
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
|
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
|
||||||
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
|
||||||
|
|||||||
+285
@@ -292,6 +292,7 @@
|
|||||||
"default": "identity",
|
"default": "identity",
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -443,6 +444,7 @@
|
|||||||
"description": "Qu\u00e9 estudio se saca del documento.",
|
"description": "Qu\u00e9 estudio se saca del documento.",
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -465,6 +467,10 @@
|
|||||||
"label": "Identidad de la persona",
|
"label": "Identidad de la persona",
|
||||||
"value": "identity"
|
"value": "identity"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
|
||||||
|
"value": "cacu_eligibility_evidence"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "Citolog\u00eda cervical",
|
"label": "Citolog\u00eda cervical",
|
||||||
"value": "cervical_cytology"
|
"value": "cervical_cytology"
|
||||||
@@ -641,6 +647,7 @@
|
|||||||
"entity": {
|
"entity": {
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -663,6 +670,10 @@
|
|||||||
"label": "Identidad de la persona",
|
"label": "Identidad de la persona",
|
||||||
"value": "identity"
|
"value": "identity"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
|
||||||
|
"value": "cacu_eligibility_evidence"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "Citolog\u00eda cervical",
|
"label": "Citolog\u00eda cervical",
|
||||||
"value": "cervical_cytology"
|
"value": "cervical_cytology"
|
||||||
@@ -1530,6 +1541,7 @@
|
|||||||
"entity": {
|
"entity": {
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -2117,6 +2129,7 @@
|
|||||||
"description": "En qu\u00e9 estudio de la plataforma se guarda.",
|
"description": "En qu\u00e9 estudio de la plataforma se guarda.",
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -2139,6 +2152,10 @@
|
|||||||
"label": "Identidad de la persona",
|
"label": "Identidad de la persona",
|
||||||
"value": "identity"
|
"value": "identity"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "Evidencia cl\u00ednica para elegibilidad CaCu",
|
||||||
|
"value": "cacu_eligibility_evidence"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "Citolog\u00eda cervical",
|
"label": "Citolog\u00eda cervical",
|
||||||
"value": "cervical_cytology"
|
"value": "cervical_cytology"
|
||||||
@@ -4056,6 +4073,7 @@
|
|||||||
"schema": {
|
"schema": {
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -4164,6 +4182,7 @@
|
|||||||
"schema": {
|
"schema": {
|
||||||
"enum": [
|
"enum": [
|
||||||
"identity",
|
"identity",
|
||||||
|
"cacu_eligibility_evidence",
|
||||||
"cervical_cytology",
|
"cervical_cytology",
|
||||||
"cervical_biopsy",
|
"cervical_biopsy",
|
||||||
"mammography",
|
"mammography",
|
||||||
@@ -5907,6 +5926,272 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/{domain}/fhir/Patient/{id}/$eligibility": {
|
||||||
|
"get": {
|
||||||
|
"description": "The normalized cohort eligibility and exclusion reasons for one CaCu patient.",
|
||||||
|
"operationId": "cacu_eligibility",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"in": "path",
|
||||||
|
"name": "domain",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Domain"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "path",
|
||||||
|
"name": "id",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"title": "Id",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Limit the report to one CaCu scenario",
|
||||||
|
"in": "query",
|
||||||
|
"name": "scenario",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Limit the report to one CaCu scenario",
|
||||||
|
"title": "Scenario"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Only index dates up to this day",
|
||||||
|
"in": "query",
|
||||||
|
"name": "cutoff",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"format": "date",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Only index dates up to this day",
|
||||||
|
"title": "Cutoff"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"content": {
|
||||||
|
"application/fhir+json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "FHIR"
|
||||||
|
},
|
||||||
|
"422": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/HTTPValidationError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Validation Error"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"summary": "Cacu Eligibility",
|
||||||
|
"tags": [
|
||||||
|
"fhir"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/{domain}/fhir/Patient/{id}/$reference-risk": {
|
||||||
|
"get": {
|
||||||
|
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The NCI/ASCCP CIN3+ reference risk of one\npatient's cytology by a cut-off, how it was resolved and, beside it, the institutional models'\nrisks when they measure the same thing. Research only: not validated, not a recommendation.",
|
||||||
|
"operationId": "reference_risk",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"in": "path",
|
||||||
|
"name": "domain",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Domain"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "path",
|
||||||
|
"name": "id",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"title": "Id",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Only what was reported by this day",
|
||||||
|
"in": "query",
|
||||||
|
"name": "cutoff",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"format": "date",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Only what was reported by this day",
|
||||||
|
"title": "Cutoff"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "The cytology's sample day",
|
||||||
|
"in": "query",
|
||||||
|
"name": "sample",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"format": "date",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "The cytology's sample day",
|
||||||
|
"title": "Sample"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"content": {
|
||||||
|
"application/fhir+json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "FHIR"
|
||||||
|
},
|
||||||
|
"422": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/HTTPValidationError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Validation Error"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"summary": "Reference Risk",
|
||||||
|
"tags": [
|
||||||
|
"fhir"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/{domain}/fhir/Patient/{id}/$risk-series": {
|
||||||
|
"get": {
|
||||||
|
"description": "EXPERIMENTAL, off unless CACU_NCI_REFERENCE=1. The risk series her record can choose to\ndraw: institutional models and NCI tables, by outcome, with the published intervals.",
|
||||||
|
"operationId": "cacu_risk_series",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"in": "path",
|
||||||
|
"name": "domain",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Domain"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"in": "path",
|
||||||
|
"name": "id",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"title": "Id",
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Only what was reported by this day",
|
||||||
|
"in": "query",
|
||||||
|
"name": "cutoff",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"format": "date",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Only what was reported by this day",
|
||||||
|
"title": "Cutoff"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "The cytology's sample day",
|
||||||
|
"in": "query",
|
||||||
|
"name": "sample",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"format": "date",
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "The cytology's sample day",
|
||||||
|
"title": "Sample"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"content": {
|
||||||
|
"application/fhir+json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "FHIR"
|
||||||
|
},
|
||||||
|
"422": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/HTTPValidationError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Validation Error"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"summary": "Cacu Risk Series",
|
||||||
|
"tags": [
|
||||||
|
"fhir"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
"/{domain}/fhir/Procedure": {
|
"/{domain}/fhir/Procedure": {
|
||||||
"get": {
|
"get": {
|
||||||
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
|
"description": "The procedures the domain's timeline infers (CaCu: colposcopies and treatments;\nCaMa: each treatment, by its kind).",
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface CacuEligibility$Params {
|
||||||
|
domain: Domain;
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Limit the report to one CaCu scenario
|
||||||
|
*/
|
||||||
|
scenario?: (string | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only index dates up to this day
|
||||||
|
*/
|
||||||
|
cutoff?: (string | null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cacuEligibility(http: HttpClient, rootUrl: string, params: CacuEligibility$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, cacuEligibility.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('id', params.id, {});
|
||||||
|
rb.query('scenario', params.scenario, {});
|
||||||
|
rb.query('cutoff', params.cutoff, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return http.request(
|
||||||
|
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
|
||||||
|
).pipe(
|
||||||
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
|
map((r: HttpResponse<any>) => {
|
||||||
|
return r as StrictHttpResponse<{
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
cacuEligibility.PATH = '/{domain}/fhir/Patient/{id}/$eligibility';
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface CacuRiskSeries$Params {
|
||||||
|
domain: Domain;
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only what was reported by this day
|
||||||
|
*/
|
||||||
|
cutoff?: (string | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cytology's sample day
|
||||||
|
*/
|
||||||
|
sample?: (string | null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cacuRiskSeries(http: HttpClient, rootUrl: string, params: CacuRiskSeries$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, cacuRiskSeries.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('id', params.id, {});
|
||||||
|
rb.query('cutoff', params.cutoff, {});
|
||||||
|
rb.query('sample', params.sample, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return http.request(
|
||||||
|
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
|
||||||
|
).pipe(
|
||||||
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
|
map((r: HttpResponse<any>) => {
|
||||||
|
return r as StrictHttpResponse<{
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
cacuRiskSeries.PATH = '/{domain}/fhir/Patient/{id}/$risk-series';
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
|
import { HttpClient, HttpContext, HttpResponse } from '@angular/common/http';
|
||||||
|
import { Observable } from 'rxjs';
|
||||||
|
import { filter, map } from 'rxjs/operators';
|
||||||
|
import { StrictHttpResponse } from '../../strict-http-response';
|
||||||
|
import { RequestBuilder } from '../../request-builder';
|
||||||
|
|
||||||
|
import { Domain } from '../../models/domain';
|
||||||
|
|
||||||
|
export interface ReferenceRisk$Params {
|
||||||
|
domain: Domain;
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only what was reported by this day
|
||||||
|
*/
|
||||||
|
cutoff?: (string | null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cytology's sample day
|
||||||
|
*/
|
||||||
|
sample?: (string | null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function referenceRisk(http: HttpClient, rootUrl: string, params: ReferenceRisk$Params, context?: HttpContext): Observable<StrictHttpResponse<{
|
||||||
|
}>> {
|
||||||
|
const rb = new RequestBuilder(rootUrl, referenceRisk.PATH, 'get');
|
||||||
|
if (params) {
|
||||||
|
rb.path('domain', params.domain, {});
|
||||||
|
rb.path('id', params.id, {});
|
||||||
|
rb.query('cutoff', params.cutoff, {});
|
||||||
|
rb.query('sample', params.sample, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return http.request(
|
||||||
|
rb.build({ responseType: 'json', accept: 'application/fhir+json', context })
|
||||||
|
).pipe(
|
||||||
|
filter((r: any): r is HttpResponse<any> => r instanceof HttpResponse),
|
||||||
|
map((r: HttpResponse<any>) => {
|
||||||
|
return r as StrictHttpResponse<{
|
||||||
|
}>;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
referenceRisk.PATH = '/{domain}/fhir/Patient/{id}/$reference-risk';
|
||||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
|||||||
|
|
||||||
|
|
||||||
export interface Conflicts$Params {
|
export interface Conflicts$Params {
|
||||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
export function conflicts(http: HttpClient, rootUrl: string, params: Conflicts$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { RequestBuilder } from '../../request-builder';
|
|||||||
|
|
||||||
|
|
||||||
export interface Held$Params {
|
export interface Held$Params {
|
||||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
export function held(http: HttpClient, rootUrl: string, params: Held$Params, context?: HttpContext): Observable<StrictHttpResponse<Array<{
|
||||||
|
|||||||
@@ -113,6 +113,12 @@ export type { SearchPatient$Params as SearchPatient$Params } from './fn/fhir/sea
|
|||||||
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
|
export { searchPatient as searchPatient } from './fn/fhir/search-patient';
|
||||||
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
|
export type { ReadPatient$Params as ReadPatient$Params } from './fn/fhir/read-patient';
|
||||||
export { readPatient as readPatient } from './fn/fhir/read-patient';
|
export { readPatient as readPatient } from './fn/fhir/read-patient';
|
||||||
|
export type { CacuEligibility$Params as CacuEligibility$Params } from './fn/fhir/cacu-eligibility';
|
||||||
|
export { cacuEligibility as cacuEligibility } from './fn/fhir/cacu-eligibility';
|
||||||
|
export type { ReferenceRisk$Params as ReferenceRisk$Params } from './fn/fhir/reference-risk';
|
||||||
|
export { referenceRisk as referenceRisk } from './fn/fhir/reference-risk';
|
||||||
|
export type { CacuRiskSeries$Params as CacuRiskSeries$Params } from './fn/fhir/cacu-risk-series';
|
||||||
|
export { cacuRiskSeries as cacuRiskSeries } from './fn/fhir/cacu-risk-series';
|
||||||
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
|
export type { SearchProcedure$Params as SearchProcedure$Params } from './fn/fhir/search-procedure';
|
||||||
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
|
export { searchProcedure as searchProcedure } from './fn/fhir/search-procedure';
|
||||||
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
|
export type { SearchRiskAssessment$Params as SearchRiskAssessment$Params } from './fn/fhir/search-risk-assessment';
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
|
* field (a mistyped record number) or a study's (a stage the scan made unreadable).
|
||||||
*/
|
*/
|
||||||
export interface Correction {
|
export interface Correction {
|
||||||
entity?: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity?: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
field: string;
|
field: string;
|
||||||
record: string;
|
record: string;
|
||||||
value: string;
|
value: string;
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export interface Extract {
|
|||||||
/**
|
/**
|
||||||
* Qué estudio se saca del documento.
|
* Qué estudio se saca del documento.
|
||||||
*/
|
*/
|
||||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
formats?: {
|
formats?: {
|
||||||
[key: string]: string;
|
[key: string]: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { Position } from '../models/position';
|
|||||||
export interface Fhir {
|
export interface Fhir {
|
||||||
column?: string;
|
column?: string;
|
||||||
concept_map?: (string | null);
|
concept_map?: (string | null);
|
||||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
id: string;
|
id: string;
|
||||||
inputs?: Array<string>;
|
inputs?: Array<string>;
|
||||||
kind?: 'fhir';
|
kind?: 'fhir';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
/* Code generated by ng-openapi-gen DO NOT EDIT. */
|
||||||
|
|
||||||
export interface Rejection {
|
export interface Rejection {
|
||||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
reason: string;
|
reason: string;
|
||||||
record: string;
|
record: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export interface Target {
|
|||||||
/**
|
/**
|
||||||
* En qué estudio de la plataforma se guarda.
|
* En qué estudio de la plataforma se guarda.
|
||||||
*/
|
*/
|
||||||
entity: 'identity' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
entity: 'identity' | 'cacu_eligibility_evidence' | 'cervical_cytology' | 'cervical_biopsy' | 'mammography' | 'breast_biopsy' | 'breast_treatment' | 'breast_recurrence' | 'clinical_note' | 'death' | 'mchat' | 'ados2' | 'eeg';
|
||||||
id: string;
|
id: string;
|
||||||
inputs?: Array<string>;
|
inputs?: Array<string>;
|
||||||
kind?: 'target';
|
kind?: 'target';
|
||||||
|
|||||||
@@ -10,12 +10,32 @@ interface Band {
|
|||||||
high?: (number | null)[];
|
high?: (number | null)[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||||
|
|
||||||
|
/** The stretches of x where the curve has both limits: a band is drawn only there, never from a
|
||||||
|
* limit that is absent (an absent limit is not zero). */
|
||||||
|
function bandRuns(b: Band): number[][] {
|
||||||
|
const runs: number[][] = [];
|
||||||
|
let run: number[] = [];
|
||||||
|
b.x.forEach((x, i) => {
|
||||||
|
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
|
||||||
|
else {
|
||||||
|
if (run.length > 1) runs.push(run);
|
||||||
|
run = [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (run.length > 1) runs.push(run);
|
||||||
|
return runs;
|
||||||
|
}
|
||||||
|
|
||||||
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
||||||
const lines: Partial<Plotly.Data>[] = [];
|
const lines: Partial<Plotly.Data>[] = [];
|
||||||
if (b.low && b.high) {
|
if (b.low && b.high) {
|
||||||
|
for (const run of bandRuns(b)) {
|
||||||
|
const x = run.map((i) => b.x[i]);
|
||||||
lines.push({
|
lines.push({
|
||||||
x: [...b.x, ...[...b.x].reverse()],
|
x: [...x, ...[...x].reverse()],
|
||||||
y: [...b.high, ...[...b.low].reverse()] as number[],
|
y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
|
||||||
fill: 'toself',
|
fill: 'toself',
|
||||||
fillcolor: `${colour}33`,
|
fillcolor: `${colour}33`,
|
||||||
line: { width: 0 },
|
line: { width: 0 },
|
||||||
@@ -24,9 +44,10 @@ function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Pl
|
|||||||
type: 'scatter',
|
type: 'scatter',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
lines.push({
|
lines.push({
|
||||||
x: b.x,
|
x: b.x,
|
||||||
y: b.y,
|
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
|
||||||
name,
|
name,
|
||||||
type: 'scatter',
|
type: 'scatter',
|
||||||
mode: 'lines',
|
mode: 'lines',
|
||||||
@@ -295,20 +316,33 @@ export function scenarioFigure(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
|
||||||
|
* point without both limits has no bar. */
|
||||||
function points(
|
function points(
|
||||||
name: string,
|
name: string,
|
||||||
x: number[],
|
x: number[],
|
||||||
p: { S: number[]; low: number[]; high: number[] },
|
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
|
||||||
): Partial<Plotly.Data> {
|
): Partial<Plotly.Data> {
|
||||||
|
const errors = p.S.map((value, i) => {
|
||||||
|
const low = p.low?.[i];
|
||||||
|
const high = p.high?.[i];
|
||||||
|
return finite(value) && finite(low) && finite(high)
|
||||||
|
? { up: high - value, down: value - low }
|
||||||
|
: null;
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
x,
|
x,
|
||||||
y: p.S,
|
y: p.S.map((v) => (finite(v) ? v : null)) as number[],
|
||||||
|
...(errors.some((error) => error !== null)
|
||||||
|
? {
|
||||||
error_y: {
|
error_y: {
|
||||||
type: 'data',
|
type: 'data' as const,
|
||||||
symmetric: false,
|
symmetric: false,
|
||||||
array: p.high.map((h, i) => h - p.S[i]),
|
array: errors.map((error) => error?.up ?? null) as number[],
|
||||||
arrayminus: p.S.map((v, i) => v - p.low[i]),
|
arrayminus: errors.map((error) => error?.down ?? null) as number[],
|
||||||
},
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
name,
|
name,
|
||||||
type: 'scatter',
|
type: 'scatter',
|
||||||
mode: 'markers',
|
mode: 'markers',
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ export type Mode = {
|
|||||||
hidden?: Hidden;
|
hidden?: Hidden;
|
||||||
}
|
}
|
||||||
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
|
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
|
||||||
|
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
|
||||||
|
| { kind: 'ratio'; measure: string; colors?: Colors }
|
||||||
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
|
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
|
||||||
/** A proportion as its two parts (what counted and what did not), in units, with the shares */
|
/** A proportion as its two parts (what counted and what did not), in units, with the shares */
|
||||||
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
|
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
|
||||||
@@ -204,6 +206,25 @@ const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
|
|||||||
/** The bars of a mode; none when the period has nothing to draw. */
|
/** The bars of a mode; none when the period has nothing to draw. */
|
||||||
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
|
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
|
||||||
switch (mode.kind) {
|
switch (mode.kind) {
|
||||||
|
case 'ratio': {
|
||||||
|
const r = of(mode.measure);
|
||||||
|
const n = r?.populations['numerator'] ?? 0;
|
||||||
|
const total = r?.populations['denominator'] ?? 0;
|
||||||
|
if (r?.score === undefined || !total) return undefined;
|
||||||
|
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
|
||||||
|
return {
|
||||||
|
head: ['n/N', '%', 'IC 95 %'],
|
||||||
|
rows: [
|
||||||
|
{
|
||||||
|
label: 'Total',
|
||||||
|
color: mode.colors?.['numerator'],
|
||||||
|
width: 100 * r.score,
|
||||||
|
marks: ends.map((v) => 100 * v),
|
||||||
|
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
case 'counts': {
|
case 'counts': {
|
||||||
const cells = of(mode.measure)?.strata['category'] ?? {};
|
const cells = of(mode.measure)?.strata['category'] ?? {};
|
||||||
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
|
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
|
||||||
|
|||||||
@@ -36,28 +36,28 @@ import { Loading } from '../loading';
|
|||||||
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
|
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
|
||||||
} @else {
|
} @else {
|
||||||
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
|
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
|
||||||
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'">
|
<mat-tab label="Resumen">
|
||||||
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
|
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
|
||||||
</mat-tab>
|
</mat-tab>
|
||||||
<mat-tab label="Trazabilidad">
|
<mat-tab label="Histórico">
|
||||||
<ng-template matTabContent>
|
<ng-template matTabContent>
|
||||||
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
|
<app-tab-trazabilidad [domain]="domain()" [measures]="measures.value()!" />
|
||||||
</ng-template>
|
</ng-template>
|
||||||
</mat-tab>
|
</mat-tab>
|
||||||
@if (domain() === 'cacu') {
|
@if (domain() === 'cacu') {
|
||||||
<mat-tab label="Análisis de riesgos">
|
<mat-tab label="Seguimiento">
|
||||||
<ng-template matTabContent>
|
<ng-template matTabContent>
|
||||||
<app-tab-riesgos [domain]="domain()" />
|
<app-tab-riesgos [domain]="domain()" />
|
||||||
</ng-template>
|
</ng-template>
|
||||||
</mat-tab>
|
</mat-tab>
|
||||||
} @else if (domain() === 'tea') {
|
} @else if (domain() === 'tea') {
|
||||||
<mat-tab label="Análisis de Riesgo">
|
<mat-tab label="Seguimiento">
|
||||||
<ng-template matTabContent>
|
<ng-template matTabContent>
|
||||||
<app-tab-riesgos-tea [domain]="domain()" />
|
<app-tab-riesgos-tea [domain]="domain()" />
|
||||||
</ng-template>
|
</ng-template>
|
||||||
</mat-tab>
|
</mat-tab>
|
||||||
} @else if (domain() === 'cama') {
|
} @else if (domain() === 'cama') {
|
||||||
<mat-tab label="Análisis de riesgos">
|
<mat-tab label="Seguimiento">
|
||||||
<ng-template matTabContent>
|
<ng-template matTabContent>
|
||||||
<app-tab-seguimiento [domain]="domain()" />
|
<app-tab-seguimiento [domain]="domain()" />
|
||||||
</ng-template>
|
</ng-template>
|
||||||
|
|||||||
@@ -13,13 +13,14 @@ export const LAYOUTS: Record<string, Layout> = {
|
|||||||
'CACU_EU7',
|
'CACU_EU7',
|
||||||
'CACU_EU_TIEMPO_REPORTE',
|
'CACU_EU_TIEMPO_REPORTE',
|
||||||
'CACU_DIAS_TOMA_DIAGNOSTICO',
|
'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||||
|
'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||||
'CACU_DIAS_TOMA_TRATAMIENTO',
|
'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||||
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||||
],
|
],
|
||||||
route: [
|
route: [
|
||||||
{
|
{
|
||||||
label: 'Resultado de citología',
|
label: 'Días de toma de citología a resultado',
|
||||||
step: 'Toma a resultado de citología',
|
step: 'Días de toma de citología a resultado',
|
||||||
fromSample: 'CACU_EU_TIEMPO_REPORTE',
|
fromSample: 'CACU_EU_TIEMPO_REPORTE',
|
||||||
fromStep: 'CACU_EU_TIEMPO_REPORTE',
|
fromStep: 'CACU_EU_TIEMPO_REPORTE',
|
||||||
},
|
},
|
||||||
@@ -36,9 +37,9 @@ export const LAYOUTS: Record<string, Layout> = {
|
|||||||
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
|
fromStep: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Diagnóstico',
|
label: 'Diagnóstico tras biopsia',
|
||||||
step: 'Del resultado de biopsia al diagnóstico',
|
step: 'Del resultado de biopsia al diagnóstico',
|
||||||
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
fromSample: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||||
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
|
fromStep: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -116,9 +116,10 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
|
|||||||
kind: 'readings',
|
kind: 'readings',
|
||||||
title,
|
title,
|
||||||
headline: measure,
|
headline: measure,
|
||||||
|
footnote: true,
|
||||||
note: `${note} Confirma la histología LIEBG o mayor.`,
|
note: `${note} Confirma la histología LIEBG o mayor.`,
|
||||||
modes: [
|
modes: [
|
||||||
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT },
|
{ kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT },
|
||||||
{
|
{
|
||||||
kind: 'shares',
|
kind: 'shares',
|
||||||
label: 'Citología previa',
|
label: 'Citología previa',
|
||||||
@@ -174,29 +175,29 @@ export const CACU: Page = {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||||
title: 'Tiempo desde la toma de muestra al resultado',
|
title: 'Días de toma de citología a resultado',
|
||||||
...CACU_DAYS,
|
...CACU_DAYS,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||||
title: 'Tiempo de tamizaje a diagnóstico',
|
title: 'Días de tamizaje a diagnóstico tras biopsia',
|
||||||
...CACU_DAYS,
|
...CACU_DAYS,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||||
title: 'Tiempo de tamizaje a tratamiento',
|
title: 'Días de tamizaje a tratamiento',
|
||||||
...CACU_DAYS,
|
...CACU_DAYS,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||||
title: 'Tiempo de diagnóstico a tratamiento',
|
title: 'Días de diagnóstico a tratamiento',
|
||||||
...CACU_DAYS,
|
...CACU_DAYS,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
opportunity: [
|
opportunity: [
|
||||||
{
|
{
|
||||||
kind: 'readings',
|
kind: 'readings',
|
||||||
title: 'Tiempos de la ruta del tamizaje',
|
title: 'Días de la ruta del tamizaje',
|
||||||
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
|
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
|
||||||
modes: [
|
modes: [
|
||||||
{
|
{
|
||||||
@@ -204,10 +205,13 @@ export const CACU: Page = {
|
|||||||
tint: TINT,
|
tint: TINT,
|
||||||
label: 'Acumulado desde la toma',
|
label: 'Acumulado desde la toma',
|
||||||
steps: [
|
steps: [
|
||||||
{ label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
|
{ label: 'Días de toma de citología a resultado', measure: 'CACU_EU_TIEMPO_REPORTE' },
|
||||||
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
|
{ label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' },
|
||||||
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
|
{ label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' },
|
||||||
{ label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' },
|
{
|
||||||
|
label: 'Diagnóstico tras biopsia',
|
||||||
|
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -216,19 +220,31 @@ export const CACU: Page = {
|
|||||||
label: 'Por pasos',
|
label: 'Por pasos',
|
||||||
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
|
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
|
||||||
steps: [
|
steps: [
|
||||||
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
|
{
|
||||||
|
label: 'Días de toma de citología a resultado',
|
||||||
|
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||||
|
},
|
||||||
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
|
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
|
||||||
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
|
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
|
||||||
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
|
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
kind: 'days-by',
|
kind: 'days',
|
||||||
tint: TINT,
|
tint: TINT,
|
||||||
label: 'Por CIE-10',
|
label: 'Primer diagnóstico',
|
||||||
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
|
steps: [{ label: 'Toma a primer diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }],
|
||||||
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
|
},
|
||||||
stratum: 'diagnosis_code',
|
{
|
||||||
|
kind: 'days',
|
||||||
|
tint: TINT,
|
||||||
|
label: 'Diagnóstico tras biopsia',
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
label: 'Toma a diagnóstico tras biopsia',
|
||||||
|
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -263,7 +279,10 @@ export const CACU: Page = {
|
|||||||
catalog: HPV,
|
catalog: HPV,
|
||||||
hidden: HPV_HIDDEN,
|
hidden: HPV_HIDDEN,
|
||||||
},
|
},
|
||||||
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', { ofAll: true, hidden: HPV_HIDDEN }),
|
...groupViews('CACU_VPH_GENOTIPO', HPV, 'reportes', {
|
||||||
|
ofAll: true,
|
||||||
|
hidden: HPV_HIDDEN,
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -289,7 +308,7 @@ export const CACU: Page = {
|
|||||||
label: 'Colposcopía',
|
label: 'Colposcopía',
|
||||||
section: ppv(
|
section: ppv(
|
||||||
'CACU_VPP_COLPOSCOPIA',
|
'CACU_VPP_COLPOSCOPIA',
|
||||||
'Valor predictivo positivo de la colposcopía',
|
'Tasa de confirmación histopatológica de referencia a colposcopía',
|
||||||
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
|
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -297,7 +316,7 @@ export const CACU: Page = {
|
|||||||
label: 'Biopsia',
|
label: 'Biopsia',
|
||||||
section: ppv(
|
section: ppv(
|
||||||
'CACU_VPP_BIOPSIA',
|
'CACU_VPP_BIOPSIA',
|
||||||
'Valor predictivo positivo de la biopsia',
|
'Tasa de confirmación histopatológica de referencia a biopsia',
|
||||||
'Pacientes con biopsia reportada, por fecha de solicitud.',
|
'Pacientes con biopsia reportada, por fecha de solicitud.',
|
||||||
{
|
{
|
||||||
kind: 'counts',
|
kind: 'counts',
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ export interface ReadingsCard {
|
|||||||
kind: 'readings';
|
kind: 'readings';
|
||||||
title: string;
|
title: string;
|
||||||
headline?: string;
|
headline?: string;
|
||||||
|
/** say the headline under the figure instead of above it */
|
||||||
|
footnote?: boolean;
|
||||||
/** what the headline proportion counts, in the plural (default: pacientes) */
|
/** what the headline proportion counts, in the plural (default: pacientes) */
|
||||||
unit?: string;
|
unit?: string;
|
||||||
note?: string;
|
note?: string;
|
||||||
@@ -263,16 +265,16 @@ export const PAGES: Record<string, Page> = {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
measure: 'CAMA_EU38A',
|
measure: 'CAMA_EU38A',
|
||||||
title: 'Tiempo de toma de mastografía a interpretación radiológica',
|
title: 'Días de toma de mastografía a interpretación radiológica',
|
||||||
...CAMA_DAYS,
|
...CAMA_DAYS,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
measure: 'CAMA_DIAS_RESULTADO_DIAGNOSTICO',
|
||||||
title: 'Tiempo de interpretación radiológica a diagnóstico',
|
title: 'Días de interpretación radiológica a diagnóstico',
|
||||||
...CAMA_DAYS,
|
...CAMA_DAYS,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Tiempo de diagnóstico a tratamiento',
|
title: 'Días de diagnóstico a tratamiento',
|
||||||
value: 'Indicador no disponible',
|
value: 'Indicador no disponible',
|
||||||
note: PENDING,
|
note: PENDING,
|
||||||
},
|
},
|
||||||
@@ -280,12 +282,12 @@ export const PAGES: Record<string, Page> = {
|
|||||||
opportunity: [
|
opportunity: [
|
||||||
{
|
{
|
||||||
kind: 'route',
|
kind: 'route',
|
||||||
title: 'Tiempo de tamizaje a diagnóstico',
|
title: 'Días de tamizaje a diagnóstico',
|
||||||
// from the mammography: only the two measures that start at it
|
// from the mammography: only the two measures that start at it
|
||||||
sample: [
|
sample: [
|
||||||
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
|
{ label: 'Interpretación radiológica', measure: 'CAMA_EU38A' },
|
||||||
{
|
{
|
||||||
label: 'Diagnóstico (tiempo total de tamizaje a diagnóstico)',
|
label: 'Diagnóstico (días de tamizaje a diagnóstico)',
|
||||||
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
measure: 'CAMA_DIAS_TOMA_DIAGNOSTICO',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -476,22 +478,27 @@ export const HISTORY: Record<string, History> = {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
{
|
{
|
||||||
title: 'Días de la toma de la citología a su resultado',
|
title: 'Días de toma de citología a resultado',
|
||||||
measure: 'CACU_EU_TIEMPO_REPORTE',
|
measure: 'CACU_EU_TIEMPO_REPORTE',
|
||||||
kind: 'median',
|
kind: 'median',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Tiempo de tamizaje a diagnóstico',
|
title: 'Días de tamizaje a primer diagnóstico',
|
||||||
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
|
||||||
kind: 'median',
|
kind: 'median',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Tiempo de tamizaje a tratamiento',
|
title: 'Días de tamizaje a diagnóstico tras biopsia',
|
||||||
|
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
|
||||||
|
kind: 'median',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Días de tamizaje a tratamiento',
|
||||||
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
|
||||||
kind: 'median',
|
kind: 'median',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Tiempo de diagnóstico a tratamiento',
|
title: 'Días de diagnóstico a tratamiento',
|
||||||
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
|
||||||
kind: 'median',
|
kind: 'median',
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -146,6 +146,9 @@ import { Reading } from './measures';
|
|||||||
} @else {
|
} @else {
|
||||||
<p class="state">Sin datos en el periodo.</p>
|
<p class="state">Sin datos en el periodo.</p>
|
||||||
}
|
}
|
||||||
|
@if (foot()) {
|
||||||
|
<p class="state">{{ foot() }}</p>
|
||||||
|
}
|
||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
:host {
|
:host {
|
||||||
@@ -347,6 +350,8 @@ export class Readings {
|
|||||||
readonly title = input.required<string>();
|
readonly title = input.required<string>();
|
||||||
readonly headline = input('');
|
readonly headline = input('');
|
||||||
readonly note = input('');
|
readonly note = input('');
|
||||||
|
/** a line under the figure */
|
||||||
|
readonly foot = input('');
|
||||||
/** the card around it names it already (tabs inside one card) */
|
/** the card around it names it already (tabs inside one card) */
|
||||||
readonly hideTitle = input(false);
|
readonly hideTitle = input(false);
|
||||||
readonly camaStyle = input(false);
|
readonly camaStyle = input(false);
|
||||||
|
|||||||
@@ -28,7 +28,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
|
|||||||
<app-readings
|
<app-readings
|
||||||
[title]="s.title"
|
[title]="s.title"
|
||||||
[camaStyle]="hasCamaHeading(s)"
|
[camaStyle]="hasCamaHeading(s)"
|
||||||
[headline]="headlineOf(s)"
|
[headline]="s.footnote ? '' : headlineOf(s)"
|
||||||
|
[foot]="footOf(s)"
|
||||||
[note]="s.note ?? ''"
|
[note]="s.note ?? ''"
|
||||||
[modes]="s.modes"
|
[modes]="s.modes"
|
||||||
[view]="view()"
|
[view]="view()"
|
||||||
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
|
|||||||
[title]="c.section.title"
|
[title]="c.section.title"
|
||||||
[hideTitle]="true"
|
[hideTitle]="true"
|
||||||
[camaStyle]="true"
|
[camaStyle]="true"
|
||||||
[headline]="headlineOf(c.section)"
|
[headline]="c.section.footnote ? '' : headlineOf(c.section)"
|
||||||
|
[foot]="footOf(c.section)"
|
||||||
[note]="c.section.note ?? ''"
|
[note]="c.section.note ?? ''"
|
||||||
[modes]="c.section.modes"
|
[modes]="c.section.modes"
|
||||||
[loading]="of().loading"
|
[loading]="of().loading"
|
||||||
@@ -162,6 +164,12 @@ export class ReadingsSection {
|
|||||||
const words = detail(measure, r, s.unit);
|
const words = detail(measure, r, s.unit);
|
||||||
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
|
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
|
||||||
}
|
}
|
||||||
|
/** The headline of a card that says it under its figure, as one line separated by commas. */
|
||||||
|
protected footOf(s: ReadingsCard): string {
|
||||||
|
return s.footnote
|
||||||
|
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
|
||||||
|
: '';
|
||||||
|
}
|
||||||
protected readonly draw = computed(() => (mode: Mode) => {
|
protected readonly draw = computed(() => (mode: Mode) => {
|
||||||
if (mode.kind !== 'figure') return undefined;
|
if (mode.kind !== 'figure') return undefined;
|
||||||
const r = this.of().reading(mode.measure);
|
const r = this.of().reading(mode.measure);
|
||||||
|
|||||||
@@ -33,10 +33,10 @@ interface Drawn {
|
|||||||
</mat-button-toggle-group>
|
</mat-button-toggle-group>
|
||||||
</section>
|
</section>
|
||||||
@if (series.isLoading()) {
|
@if (series.isLoading()) {
|
||||||
<app-loading what="la trazabilidad" text="Cargando trazabilidad…" />
|
<app-loading what="el histórico" text="Cargando histórico…" />
|
||||||
} @else if (series.error()) {
|
} @else if (series.error()) {
|
||||||
<p class="muted" role="alert">
|
<p class="muted" role="alert">
|
||||||
No se pudo cargar la trazabilidad.
|
No se pudo cargar el histórico.
|
||||||
<button type="button" class="retry" (click)="series.reload()">Reintentar</button>
|
<button type="button" class="retry" (click)="series.reload()">Reintentar</button>
|
||||||
</p>
|
</p>
|
||||||
} @else {
|
} @else {
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import type { Parameters } from 'fhir/r4';
|
||||||
|
import { eligibilityFailure, eligibilityView } from './eligibility';
|
||||||
|
|
||||||
|
const part = (name: string, extra: object) => ({ name, ...extra }) as any;
|
||||||
|
const SCENARIOS = 'https://isssteleon.org/fhir/CodeSystem/cacu-eligibility-scenario';
|
||||||
|
const CRITERIA = 'https://isssteleon.org/fhir/CodeSystem/cacu-exclusion-criterion';
|
||||||
|
const candidate = (
|
||||||
|
scenario: string,
|
||||||
|
date: string,
|
||||||
|
eligible: boolean,
|
||||||
|
criteria: string[] = [],
|
||||||
|
sample?: string,
|
||||||
|
display?: string,
|
||||||
|
) =>
|
||||||
|
part('candidate', {
|
||||||
|
part: [
|
||||||
|
part('scenario', { valueCoding: { system: SCENARIOS, code: scenario, display } }),
|
||||||
|
part('index-date', { valueDate: date }),
|
||||||
|
...(sample ? [part('index-sample-id', { valueString: sample })] : []),
|
||||||
|
part('eligible', { valueBoolean: eligible }),
|
||||||
|
...criteria.map((c) => part('criterion', { valueCoding: { system: CRITERIA, code: c } })),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const answer = (status: string, ...candidates: object[]): Parameters =>
|
||||||
|
({
|
||||||
|
resourceType: 'Parameters',
|
||||||
|
parameter: [
|
||||||
|
part('status', { valueCode: status }),
|
||||||
|
part('patient', { valueReference: { reference: 'Patient/p' } }),
|
||||||
|
part('cutoff', { valueDate: '2026-12-02' }),
|
||||||
|
...candidates,
|
||||||
|
],
|
||||||
|
}) as Parameters;
|
||||||
|
|
||||||
|
// Each test fails if the section merged visits, dropped a reason or read silence as eligibility.
|
||||||
|
describe('the eligibility answer as the section shows it', () => {
|
||||||
|
it('groups by scenario, keeps each visit apart, with its own decision and all its reasons', () => {
|
||||||
|
const view = eligibilityView(
|
||||||
|
answer(
|
||||||
|
'evaluated',
|
||||||
|
candidate(
|
||||||
|
'post_colposcopy',
|
||||||
|
'2020-08-10',
|
||||||
|
false,
|
||||||
|
['cancer_history', 'outcome_by_index', 'prior_treatment'],
|
||||||
|
'2020-08-10',
|
||||||
|
),
|
||||||
|
candidate('surveillance', '2024-01-05', true, [], 'a'),
|
||||||
|
candidate('surveillance', '2025-03-01', false, ['no_index_result'], 'b'),
|
||||||
|
candidate('post_colposcopy', '2022-02-02', true, [], '2022-02-02'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (view.kind !== 'evaluated') throw new Error(view.kind);
|
||||||
|
expect(view.cutoff).toBe('2026-12-02');
|
||||||
|
expect(view.groups.map((g) => [g.code, g.text, g.visits.length])).toEqual([
|
||||||
|
['post_colposcopy', 'Postcolposcopia', 2],
|
||||||
|
['surveillance', 'Vigilancia', 2],
|
||||||
|
]);
|
||||||
|
const post = view.groups[0].visits; // newest visit first
|
||||||
|
expect(post.map((v) => [v.indexDate, v.eligible, v.reasons.map((r) => r.code)])).toEqual([
|
||||||
|
['2022-02-02', true, []],
|
||||||
|
['2020-08-10', false, ['cancer_history', 'outcome_by_index', 'prior_treatment']],
|
||||||
|
]);
|
||||||
|
expect(post[1].reasons[0].text).toBe('Antecedente de cáncer cervicouterino');
|
||||||
|
expect(view.groups[1].visits.map((v) => v.sampleId)).toEqual(['b', 'a']);
|
||||||
|
});
|
||||||
|
it('the backend decides: a visit it calls eligible is eligible, one with reasons is not derived', () => {
|
||||||
|
const view = eligibilityView(answer('evaluated', candidate('survival', '2025-01-01', true)));
|
||||||
|
if (view.kind !== 'evaluated') throw new Error(view.kind);
|
||||||
|
expect(view.groups[0].visits[0]).toMatchObject({
|
||||||
|
eligible: true,
|
||||||
|
reasons: [],
|
||||||
|
sampleId: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
it('without candidates it says so, which is not eligibility', () => {
|
||||||
|
expect(eligibilityView(answer('no_candidate'))).toEqual({ kind: 'none', cutoff: '2026-12-02' });
|
||||||
|
});
|
||||||
|
it('an answer that is not the contract is "unavailable", never an empty list of reasons', () => {
|
||||||
|
for (const bad of [
|
||||||
|
null,
|
||||||
|
undefined,
|
||||||
|
{} as any,
|
||||||
|
{ resourceType: 'Bundle' } as any,
|
||||||
|
answer('evaluated'),
|
||||||
|
answer('other', candidate('survival', '2025-01-01', true)),
|
||||||
|
answer('evaluated', part('candidate', { part: [] })),
|
||||||
|
])
|
||||||
|
expect(eligibilityView(bad)).toEqual({ kind: 'unavailable' });
|
||||||
|
});
|
||||||
|
it('unknown codes show the display the API gave, else the code, and keep the code', () => {
|
||||||
|
const view = eligibilityView(
|
||||||
|
answer(
|
||||||
|
'evaluated',
|
||||||
|
candidate('new_scenario', '2025-01-01', false, ['new_rule'], undefined, 'Escenario nuevo'),
|
||||||
|
candidate('other_scenario', '2025-01-02', false, ['another_rule']),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (view.kind !== 'evaluated') throw new Error(view.kind);
|
||||||
|
expect(view.groups.map((g) => [g.code, g.text])).toEqual([
|
||||||
|
['new_scenario', 'Escenario nuevo'],
|
||||||
|
['other_scenario', 'other_scenario'],
|
||||||
|
]);
|
||||||
|
expect(view.groups[1].visits[0].reasons).toEqual([
|
||||||
|
{ code: 'another_rule', text: 'another_rule' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('what a failed call is', () => {
|
||||||
|
const failure = (status: number, error: unknown = null) =>
|
||||||
|
eligibilityFailure(new HttpErrorResponse({ status, error }));
|
||||||
|
it('a 409 asks for the gold update and keeps the backend diagnostics', () => {
|
||||||
|
expect(
|
||||||
|
failure(409, {
|
||||||
|
resourceType: 'OperationOutcome',
|
||||||
|
issue: [{ code: 'conflict', diagnostics: 'rebuild gold.cacu_eligibility' }],
|
||||||
|
}),
|
||||||
|
).toEqual({ kind: 'gold', text: 'rebuild gold.cacu_eligibility' });
|
||||||
|
expect(failure(409)).toEqual({ kind: 'gold', text: undefined });
|
||||||
|
});
|
||||||
|
it('404 and 422 are "unavailable"; any other status or no connection is a communication error', () => {
|
||||||
|
expect(failure(404)).toEqual({ kind: 'unavailable' });
|
||||||
|
expect(failure(422)).toEqual({ kind: 'unavailable' });
|
||||||
|
expect(failure(500)).toEqual({ kind: 'error' });
|
||||||
|
expect(failure(0)).toEqual({ kind: 'error' });
|
||||||
|
expect(eligibilityFailure(new Error('boom'))).toEqual({ kind: 'error' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
import { HttpErrorResponse } from '@angular/common/http';
|
||||||
|
import { Component, input } from '@angular/core';
|
||||||
|
import type { Parameters, ParametersParameter } from 'fhir/r4';
|
||||||
|
|
||||||
|
/** The clinical scenarios the backend publishes, as the screens name them (the API's codes stay). */
|
||||||
|
export const SCENARIO_TEXT: Record<string, string> = {
|
||||||
|
surveillance: 'Vigilancia',
|
||||||
|
pre_colposcopy: 'Precolposcopia',
|
||||||
|
post_colposcopy: 'Postcolposcopia',
|
||||||
|
post_colposcopy_second_visit: 'Segunda visita postcolposcopia',
|
||||||
|
post_treatment: 'Postratamiento',
|
||||||
|
survival: 'Supervivencia',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The exclusion criteria the backend publishes, as the screens say them. */
|
||||||
|
export const CRITERION_TEXT: Record<string, string> = {
|
||||||
|
hysterectomy: 'Histerectomía previa al índice',
|
||||||
|
under_18: 'Edad menor de 18 años al índice',
|
||||||
|
prior_outcome: 'Resultado CIN2+ previo al índice',
|
||||||
|
no_index_result: 'Sin resultado de citología o VPH en la visita índice',
|
||||||
|
unreported_biopsy: 'Biopsia solicitada sin resultado',
|
||||||
|
outcome_by_index: 'Resultado CIN2+ hasta la visita índice',
|
||||||
|
cancer_history: 'Antecedente de cáncer cervicouterino',
|
||||||
|
prior_treatment: 'Tratamiento previo a la visita índice',
|
||||||
|
no_referral: 'Sin resultado que sustente la referencia a colposcopia',
|
||||||
|
no_cotest: 'Sin cotest de citología y VPH en la visita índice',
|
||||||
|
no_pretreatment_biopsy: 'Sin biopsia previa al tratamiento en el periodo requerido',
|
||||||
|
outcome_before_index: 'Resultado CIN2+ entre tratamiento e índice',
|
||||||
|
no_birth_date: 'Fecha de nacimiento desconocida',
|
||||||
|
died_by_index: 'Defunción en o antes de la visita índice',
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface Reason {
|
||||||
|
/** the API's code, untouched */
|
||||||
|
code: string;
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
export interface Visit {
|
||||||
|
indexDate: string;
|
||||||
|
/** the sample the visit is evaluated at, when the backend names one */
|
||||||
|
sampleId?: string;
|
||||||
|
/** the backend's decision; it is never derived from the reasons */
|
||||||
|
eligible: boolean;
|
||||||
|
reasons: Reason[];
|
||||||
|
}
|
||||||
|
export interface ScenarioGroup {
|
||||||
|
code: string;
|
||||||
|
text: string;
|
||||||
|
visits: Visit[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the section can be in; none of them says "eligible" unless the backend did. */
|
||||||
|
export type EligibilityState =
|
||||||
|
| { kind: 'loading' }
|
||||||
|
| { kind: 'error' }
|
||||||
|
| { kind: 'unavailable' }
|
||||||
|
| { kind: 'gold'; text?: string }
|
||||||
|
| { kind: 'none'; cutoff?: string }
|
||||||
|
| { kind: 'evaluated'; cutoff?: string; groups: ScenarioGroup[] };
|
||||||
|
|
||||||
|
type Part = ParametersParameter;
|
||||||
|
const value = (p?: Part): unknown =>
|
||||||
|
p?.valueCode ?? p?.valueString ?? p?.valueDate ?? p?.valueBoolean ?? undefined;
|
||||||
|
const named = (parts: Part[] | undefined, name: string) =>
|
||||||
|
(parts ?? []).filter((p) => p.name === name);
|
||||||
|
const coding = (p?: Part) => p?.valueCoding;
|
||||||
|
|
||||||
|
/** The answer of `$eligibility`, grouped by scenario and keeping the visits apart: each visit has
|
||||||
|
* its own decision and its own reasons. A code the screens do not know shows the display the API
|
||||||
|
* gave, else the code itself. An answer that is not what the contract says is "unavailable". */
|
||||||
|
export function eligibilityView(answer: Parameters | null | undefined): EligibilityState {
|
||||||
|
const top = answer?.parameter;
|
||||||
|
if (answer?.resourceType !== 'Parameters' || !Array.isArray(top)) return { kind: 'unavailable' };
|
||||||
|
const status = value(named(top, 'status')[0]);
|
||||||
|
const cutoff = value(named(top, 'cutoff')[0]) as string | undefined;
|
||||||
|
const candidates = named(top, 'candidate');
|
||||||
|
if (status === 'no_candidate' && !candidates.length) return { kind: 'none', cutoff };
|
||||||
|
if (status !== 'evaluated' || !candidates.length) return { kind: 'unavailable' };
|
||||||
|
const groups = new Map<string, ScenarioGroup>();
|
||||||
|
for (const c of candidates) {
|
||||||
|
const scenario = coding(named(c.part, 'scenario')[0]);
|
||||||
|
const indexDate = value(named(c.part, 'index-date')[0]) as string | undefined;
|
||||||
|
const eligible = value(named(c.part, 'eligible')[0]);
|
||||||
|
if (!scenario?.code || !indexDate || typeof eligible !== 'boolean')
|
||||||
|
return { kind: 'unavailable' };
|
||||||
|
const group = groups.get(scenario.code) ?? {
|
||||||
|
code: scenario.code,
|
||||||
|
text: SCENARIO_TEXT[scenario.code] ?? scenario.display ?? scenario.code,
|
||||||
|
visits: [],
|
||||||
|
};
|
||||||
|
groups.set(scenario.code, group);
|
||||||
|
group.visits.push({
|
||||||
|
indexDate,
|
||||||
|
sampleId: value(named(c.part, 'index-sample-id')[0]) as string | undefined,
|
||||||
|
eligible,
|
||||||
|
reasons: named(c.part, 'criterion').flatMap((r) => {
|
||||||
|
const k = coding(r);
|
||||||
|
return k?.code
|
||||||
|
? [{ code: k.code, text: CRITERION_TEXT[k.code] ?? k.display ?? k.code }]
|
||||||
|
: [];
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const g of groups.values()) g.visits.sort((a, b) => b.indexDate.localeCompare(a.indexDate));
|
||||||
|
return { kind: 'evaluated', cutoff, groups: [...groups.values()] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the answer's failure says: the gold must be updated (409), the patient has no such
|
||||||
|
* operation (404, 422), or the call itself failed (anything else, including no connection). */
|
||||||
|
export function eligibilityFailure(error: unknown): EligibilityState {
|
||||||
|
if (error instanceof HttpErrorResponse) {
|
||||||
|
if (error.status === 409) {
|
||||||
|
const issue = (error.error as { issue?: { diagnostics?: string }[] } | null)?.issue?.[0];
|
||||||
|
return { kind: 'gold', text: issue?.diagnostics };
|
||||||
|
}
|
||||||
|
if (error.status === 404 || error.status === 422) return { kind: 'unavailable' };
|
||||||
|
}
|
||||||
|
return { kind: 'error' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
|
||||||
|
|
||||||
|
/** "Elegibilidad por escenario clínico": the decisions the backend publishes for each indexed visit,
|
||||||
|
* one scenario at a time. It shows them; it decides nothing. */
|
||||||
|
@Component({
|
||||||
|
selector: 'app-eligibility',
|
||||||
|
template: `
|
||||||
|
@let s = state();
|
||||||
|
@switch (s.kind) {
|
||||||
|
@case ('loading') {
|
||||||
|
<p class="state" role="status" data-state="loading">Consultando la elegibilidad…</p>
|
||||||
|
}
|
||||||
|
@case ('error') {
|
||||||
|
<p class="state" role="alert" data-state="error">
|
||||||
|
No se pudo consultar la elegibilidad. Intente de nuevo más tarde.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@case ('unavailable') {
|
||||||
|
<p class="state" role="status" data-state="unavailable">
|
||||||
|
Información de elegibilidad no disponible para esta paciente.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@case ('gold') {
|
||||||
|
<p class="state" role="status" data-state="gold">
|
||||||
|
La elegibilidad requiere actualizar la capa gold del servidor; todavía no está disponible.
|
||||||
|
</p>
|
||||||
|
@if (s.text) {
|
||||||
|
<p class="muted detail">{{ s.text }}</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@case ('none') {
|
||||||
|
<p class="state" role="status" data-state="none">
|
||||||
|
Sin candidatos: la paciente no tiene visitas indexadas en estos escenarios
|
||||||
|
@if (s.cutoff) {
|
||||||
|
a la fecha de corte {{ s.cutoff }}
|
||||||
|
}
|
||||||
|
. Esto no significa que sea elegible.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@case ('evaluated') {
|
||||||
|
@for (g of s.groups; track g.code) {
|
||||||
|
<details class="scenario" [attr.data-scenario]="g.code" [open]="g.visits.length <= 2">
|
||||||
|
<summary>
|
||||||
|
<strong>{{ g.text }}</strong>
|
||||||
|
<span class="muted">
|
||||||
|
· {{ plural(g.visits.length, 'visita', 'visitas') }} ·
|
||||||
|
{{ plural(count(g, true), 'elegible', 'elegibles') }},
|
||||||
|
{{ plural(count(g, false), 'no elegible', 'no elegibles') }}
|
||||||
|
</span>
|
||||||
|
</summary>
|
||||||
|
<ul class="visits">
|
||||||
|
@for (v of g.visits; track $index) {
|
||||||
|
<li class="visit" [attr.data-eligible]="v.eligible">
|
||||||
|
<p class="head">
|
||||||
|
<span class="badge" [class.ok]="v.eligible">{{
|
||||||
|
v.eligible ? 'Elegible' : 'No elegible'
|
||||||
|
}}</span>
|
||||||
|
Fecha índice {{ v.indexDate }}
|
||||||
|
<span class="muted"
|
||||||
|
>· {{ v.sampleId ? 'Muestra ' + v.sampleId : 'Sin muestra asociada' }}</span
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
@if (v.reasons.length) {
|
||||||
|
<ul class="why" aria-label="Motivos de exclusión">
|
||||||
|
@for (r of v.reasons; track r.code) {
|
||||||
|
<li [attr.data-code]="r.code">{{ r.text }}</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
@if (s.cutoff) {
|
||||||
|
<p class="muted note">Visitas hasta la fecha de corte {{ s.cutoff }}.</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
.note,
|
||||||
|
.detail {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.state {
|
||||||
|
margin: 8px 0;
|
||||||
|
}
|
||||||
|
.scenario {
|
||||||
|
border-top: 1px solid #dce3e7;
|
||||||
|
padding: 6px 0;
|
||||||
|
}
|
||||||
|
.scenario summary {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.visits {
|
||||||
|
list-style: none;
|
||||||
|
margin: 6px 0 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.visit {
|
||||||
|
padding: 4px 0 4px 12px;
|
||||||
|
}
|
||||||
|
.head {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.badge {
|
||||||
|
background: #f3d6dc;
|
||||||
|
border-radius: 10px;
|
||||||
|
color: #7a1f36;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
margin-right: 6px;
|
||||||
|
padding: 1px 8px;
|
||||||
|
}
|
||||||
|
.badge.ok {
|
||||||
|
background: #dcefe4;
|
||||||
|
color: #1d5a3b;
|
||||||
|
}
|
||||||
|
.why {
|
||||||
|
margin: 2px 0 0;
|
||||||
|
padding-left: 22px;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class Eligibility {
|
||||||
|
readonly state = input.required<EligibilityState>();
|
||||||
|
protected plural = plural;
|
||||||
|
protected count(g: ScenarioGroup, eligible: boolean) {
|
||||||
|
return g.visits.filter((v) => v.eligible === eligible).length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { EligibilityState, Visit } from './eligibility';
|
||||||
|
import { ineligibility } from './ineligibility';
|
||||||
|
|
||||||
|
const visit = (indexDate: string, ...reasons: string[]): Visit => ({
|
||||||
|
indexDate,
|
||||||
|
eligible: !reasons.length,
|
||||||
|
reasons: reasons.map((text) => ({ code: text, text })),
|
||||||
|
});
|
||||||
|
const state: EligibilityState = {
|
||||||
|
kind: 'evaluated',
|
||||||
|
groups: [
|
||||||
|
{
|
||||||
|
code: 'pre_colposcopy',
|
||||||
|
text: 'Precolposcopia',
|
||||||
|
visits: [visit('2025-01-01', 'Histerectomía previa al índice'), visit('2024-01-01')],
|
||||||
|
},
|
||||||
|
{ code: 'post_treatment', text: 'Postratamiento', visits: [visit('2025-01-01', 'Otro')] },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('ineligibility', () => {
|
||||||
|
it('speaks only when she is not eligible in her own scenario', () => {
|
||||||
|
expect(ineligibility(state, 'pre_colposcopy', '2025-06-01')).toBe(
|
||||||
|
'No disponible por: Histerectomía previa al índice.',
|
||||||
|
);
|
||||||
|
expect(ineligibility(state, 'pre_colposcopy', '2024-06-01')).toBeUndefined();
|
||||||
|
expect(ineligibility(state, 'post_colposcopy', '2025-06-01')).toBeUndefined();
|
||||||
|
expect(ineligibility(state, 'case', '2025-06-01')).toBeUndefined();
|
||||||
|
expect(ineligibility({ kind: 'error' }, 'pre_colposcopy', '2025-06-01')).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { EligibilityState } from './eligibility';
|
||||||
|
|
||||||
|
/** The `$eligibility` scenarios that stand for each follow-up status, the first that has a
|
||||||
|
* visit speaking for her. A case has no disease-risk estimate to be eligible for. */
|
||||||
|
const SCENARIOS: Record<string, string[]> = {
|
||||||
|
pre_colposcopy: ['pre_colposcopy', 'surveillance'],
|
||||||
|
post_colposcopy: ['post_colposcopy'],
|
||||||
|
post_treatment: ['post_treatment'],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** What the risk section says when she is not eligible in her clinical scenario, from its latest
|
||||||
|
* visit indexed by `day`; nothing when she is eligible or the backend has no visit of it. */
|
||||||
|
export function ineligibility(
|
||||||
|
state: EligibilityState,
|
||||||
|
status: string,
|
||||||
|
day: string,
|
||||||
|
): string | undefined {
|
||||||
|
if (state.kind !== 'evaluated') return undefined;
|
||||||
|
for (const scenario of SCENARIOS[status] ?? []) {
|
||||||
|
// visits come latest first
|
||||||
|
const latest = state.groups
|
||||||
|
.find((g) => g.code === scenario)
|
||||||
|
?.visits.find((v) => v.indexDate <= day);
|
||||||
|
if (latest) {
|
||||||
|
return latest.eligible
|
||||||
|
? undefined
|
||||||
|
: `No disponible por: ${latest.reasons.map((r) => r.text).join('; ')}.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
+102
-32
@@ -121,13 +121,6 @@
|
|||||||
}
|
}
|
||||||
<div data-section="etapas">
|
<div data-section="etapas">
|
||||||
<app-stages [stages]="s" [detail]="true" />
|
<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>
|
</div>
|
||||||
}
|
}
|
||||||
<table class="plain">
|
<table class="plain">
|
||||||
@@ -253,20 +246,17 @@
|
|||||||
</mat-card>
|
</mat-card>
|
||||||
}
|
}
|
||||||
|
|
||||||
<mat-card appearance="outlined" class="wide">
|
@if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) {
|
||||||
<mat-card-header
|
<mat-card appearance="outlined" class="wide" data-section="riesgos">
|
||||||
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
|
|
||||||
>
|
|
||||||
<mat-card-content>
|
<mat-card-content>
|
||||||
@if (riskExclusion(); as reason) {
|
@if (riskExclusion(); as reason) {
|
||||||
<p role="status">{{ reason }}</p>
|
<p role="status">{{ reason }}</p>
|
||||||
} @else {
|
} @else {
|
||||||
<app-risk-scales [groups]="groups()" />
|
<app-risk-scales [groups]="groups()" />
|
||||||
@if (reference.value(); as ref) {
|
|
||||||
<app-reference-risk [view]="ref" />
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@if (riskModels().length) {
|
@if (riskModels().length) {
|
||||||
|
<details data-section="modelos">
|
||||||
|
<summary>Modelos y valores</summary>
|
||||||
<table class="plain">
|
<table class="plain">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -287,7 +277,9 @@
|
|||||||
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
|
<td>{{ p.p * 100 | number: '1.1-2' }} %</td>
|
||||||
<td>
|
<td>
|
||||||
@if (p.low !== undefined) {
|
@if (p.low !== undefined) {
|
||||||
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }}
|
{{ p.low * 100 | number: '1.1-2' }}–{{
|
||||||
|
p.high! * 100 | number: '1.1-2'
|
||||||
|
}}
|
||||||
%
|
%
|
||||||
} @else {
|
} @else {
|
||||||
—
|
—
|
||||||
@@ -298,21 +290,24 @@
|
|||||||
}
|
}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
|
||||||
<details class="curves" open data-section="curvas">
|
<details class="curves" open data-section="curvas">
|
||||||
<summary>Curvas de probabilidad con su intervalo</summary>
|
<summary>Curvas de probabilidad con su intervalo</summary>
|
||||||
<ul class="curve-text">
|
@if (riskSeries.value()?.length) {
|
||||||
@for (t of curveText(); track $index) {
|
<app-risk-series [series]="riskSeries.value()!" />
|
||||||
<li>{{ t }}</li>
|
} @else {
|
||||||
|
<app-plot [figure]="curve()" [height]="300" [toolbar]="false" />
|
||||||
}
|
}
|
||||||
</ul>
|
|
||||||
<app-plot [figure]="curve()" [height]="300" />
|
|
||||||
</details>
|
</details>
|
||||||
} @else if (!riskExclusion()) {
|
}
|
||||||
|
@if (!riskModels().length && !riskExclusion()) {
|
||||||
<p class="muted">Sin evaluación de un modelo en producción.</p>
|
<p class="muted">Sin evaluación de un modelo en producción.</p>
|
||||||
}
|
}
|
||||||
</mat-card-content>
|
</mat-card-content>
|
||||||
</mat-card>
|
</mat-card>
|
||||||
|
}
|
||||||
@if (domain() === 'tea') {
|
@if (domain() === 'tea') {
|
||||||
<mat-card appearance="outlined" class="wide" data-section="tea">
|
<mat-card appearance="outlined" class="wide" data-section="tea">
|
||||||
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
|
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
|
||||||
@@ -560,23 +555,76 @@
|
|||||||
</mat-card-content>
|
</mat-card-content>
|
||||||
</mat-card>
|
</mat-card>
|
||||||
}
|
}
|
||||||
@if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) {
|
@if (models().some((m) => m.model.endsWith('.survival'))) {
|
||||||
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
|
<mat-card appearance="outlined" class="wide" data-section="supervivencia">
|
||||||
<mat-card-header>
|
<mat-card-header>
|
||||||
<mat-card-title>{{
|
<mat-card-title>{{
|
||||||
domain() === 'cacu' ? 'Supervivencia por escenario clínico' : 'Riesgo de muerte'
|
domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
|
||||||
}}</mat-card-title>
|
}}</mat-card-title>
|
||||||
</mat-card-header>
|
</mat-card-header>
|
||||||
<mat-card-content>
|
<mat-card-content>
|
||||||
|
@if (domain() !== 'cacu') {
|
||||||
<h3>Análisis de supervivencia</h3>
|
<h3>Análisis de supervivencia</h3>
|
||||||
|
}
|
||||||
@if (domain() === 'cacu') {
|
@if (domain() === 'cacu') {
|
||||||
<p class="muted" data-note="grupo">
|
<app-risk-scales [groups]="survivalScales()" />
|
||||||
Las curvas son estimaciones del grupo de pacientes del escenario clínico
|
@for (g of survivalScales(); track $index) {
|
||||||
correspondiente (S(t), probabilidad de supervivencia); no son predicciones
|
<details data-section="valores-supervivencia">
|
||||||
individuales.
|
<summary>Modelos y valores</summary>
|
||||||
|
<table class="plain">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Modelo</th>
|
||||||
|
<th>Fecha índice</th>
|
||||||
|
<th>Horizonte</th>
|
||||||
|
<th>Supervivencia</th>
|
||||||
|
<th>IC 95 %</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@for (v of g.scales; track v.label) {
|
||||||
|
<tr>
|
||||||
|
<td>{{ $first ? g.model : '' }}</td>
|
||||||
|
<td>{{ $first ? g.index : '' }}</td>
|
||||||
|
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
|
||||||
|
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
|
||||||
|
<td>
|
||||||
|
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
|
||||||
|
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
|
||||||
|
v.risk!.high! * 100 | number: '1.1-2'
|
||||||
|
}}
|
||||||
|
%
|
||||||
|
} @else {
|
||||||
|
—
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
<h3>Curva de supervivencia</h3>
|
||||||
|
@if (combination.isLoading()) {
|
||||||
|
<app-loading what="la curva de supervivencia" [figure]="true" />
|
||||||
|
} @else if (combination.error()) {
|
||||||
|
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
||||||
|
} @else if (combination.value(); as c) {
|
||||||
|
@if (c.figure) {
|
||||||
|
<p class="muted">
|
||||||
|
Kaplan-Meier de pacientes con sus mismos valores (IC 95 % Greenwood log-log; n =
|
||||||
|
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
|
||||||
|
</p>
|
||||||
|
<app-plot [figure]="c.figure" [height]="340" [toolbar]="false" />
|
||||||
|
} @else {
|
||||||
|
<p class="muted">{{ c.missing }}</p>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<p class="muted">
|
||||||
|
No disponible: la estimación no conserva los valores usados para elegir la curva.
|
||||||
</p>
|
</p>
|
||||||
}
|
}
|
||||||
@if (survival.isLoading()) {
|
} @else if (survival.isLoading()) {
|
||||||
<app-loading what="las curvas de supervivencia" [figure]="true" />
|
<app-loading what="las curvas de supervivencia" [figure]="true" />
|
||||||
} @else if (survival.value(); as s) {
|
} @else if (survival.value(); as s) {
|
||||||
<h3>Escenario clínico de la paciente</h3>
|
<h3>Escenario clínico de la paciente</h3>
|
||||||
@@ -585,17 +633,39 @@
|
|||||||
<li>{{ name }}</li>
|
<li>{{ name }}</li>
|
||||||
}
|
}
|
||||||
</ul>
|
</ul>
|
||||||
|
@if (s.methods.length) {
|
||||||
|
<details>
|
||||||
|
<summary>Métodos</summary>
|
||||||
|
<ul class="scenarios methods">
|
||||||
|
@for (name of s.methods; track name) {
|
||||||
|
<li>{{ name }}</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
@for (f of s.figures; track f.title) {
|
@for (f of s.figures; track f.title) {
|
||||||
<h4>{{ f.title }}</h4>
|
<h4>{{ f.title }}</h4>
|
||||||
<app-plot [figure]="f.figure" [height]="340" />
|
<app-plot [figure]="f.figure" [height]="340" />
|
||||||
} @empty {
|
}
|
||||||
<p class="muted">
|
@for (name of s.unavailable; track name) {
|
||||||
Sus escenarios no tienen fallecimientos suficientes para trazar curvas.
|
<h4>{{ name }}</h4>
|
||||||
|
<p class="muted">No disponible: datos insuficientes.</p>
|
||||||
|
}
|
||||||
|
@for (u of s.insufficient; track u.name) {
|
||||||
|
<h4>{{ u.name }}</h4>
|
||||||
|
<p class="muted" data-state="insuficiente">{{ insufficientText(u) }}</p>
|
||||||
|
}
|
||||||
|
@for (name of s.missing; track name) {
|
||||||
|
<h4>{{ name }}</h4>
|
||||||
|
<p class="muted" data-state="sin-informacion">
|
||||||
|
Sin información de este escenario en el informe del modelo.
|
||||||
</p>
|
</p>
|
||||||
}
|
}
|
||||||
<app-factores [rows]="s.factors" />
|
<app-factores [rows]="s.factors" />
|
||||||
} @else if (survival.error()) {
|
} @else if (survival.error()) {
|
||||||
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
|
||||||
|
} @else {
|
||||||
|
<p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
|
||||||
}
|
}
|
||||||
</mat-card-content>
|
</mat-card-content>
|
||||||
</mat-card>
|
</mat-card>
|
||||||
|
|||||||
+142
-29
@@ -13,6 +13,8 @@ import type {
|
|||||||
RiskAssessment,
|
RiskAssessment,
|
||||||
} from 'fhir/r4';
|
} from 'fhir/r4';
|
||||||
import { Api } from '../api/api';
|
import { Api } from '../api/api';
|
||||||
|
import { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
|
||||||
|
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
|
||||||
import { studies as eegStudies } from '../api/fn/eeg/studies';
|
import { studies as eegStudies } from '../api/fn/eeg/studies';
|
||||||
import { study as eegStudy } from '../api/fn/eeg/study';
|
import { study as eegStudy } from '../api/fn/eeg/study';
|
||||||
import { readReport$Json } from '../api/fn/models/read-report-json';
|
import { readReport$Json } from '../api/fn/models/read-report-json';
|
||||||
@@ -25,10 +27,13 @@ import { HttpClient } from '@angular/common/http';
|
|||||||
import type { Parameters as FhirParameters } from 'fhir/r4';
|
import type { Parameters as FhirParameters } from 'fhir/r4';
|
||||||
import { firstValueFrom } from 'rxjs';
|
import { firstValueFrom } from 'rxjs';
|
||||||
import { ApiConfiguration } from '../api/api-configuration';
|
import { ApiConfiguration } from '../api/api-configuration';
|
||||||
import { ANTECEDENTS, Fact, group, split } from './record-groups';
|
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
|
||||||
import { referenceView, ReferenceRisk, ReferenceView } from './reference-risk';
|
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
|
||||||
import { curveFigure, curveText } from './risk-curve';
|
import { ineligibility } from './ineligibility';
|
||||||
import { isRiskModel, riskGroups, riskScales, RiskScales } from './risk-scales';
|
import { parseSeries, RiskSeries, Series } from './risk-series';
|
||||||
|
import { curveFigure } from './risk-curve';
|
||||||
|
import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
|
||||||
|
import { combinationFigure, combinationOf, noCurveText } from './survival-combination';
|
||||||
import { route, Stages } from './stages';
|
import { route, Stages } from './stages';
|
||||||
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
|
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
|
||||||
import { LABELS, name, PRIORITY } from '../indicadores/measures';
|
import { LABELS, name, PRIORITY } from '../indicadores/measures';
|
||||||
@@ -69,6 +74,31 @@ function facts(observations: Observation[]): Fact[] {
|
|||||||
|
|
||||||
/** One patient: her history (conditions, procedures), her tests and results, and the
|
/** One patient: her history (conditions, procedures), her tests and results, and the
|
||||||
* champion models' risks with their curves. Everything read from the FHIR API. */
|
* champion models' risks with their curves. Everything read from the FHIR API. */
|
||||||
|
/** The names of the methods the figures draw, each once. */
|
||||||
|
function methods(figures: { figure: { data: unknown[] } }[]): string[] {
|
||||||
|
const names = figures.flatMap((f) => f.figure.data.map((t) => (t as { name?: string }).name));
|
||||||
|
return [...new Set(names.filter((n): n is string => !!n))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The day of an instant in the hospital's time zone (America/Monterrey). */
|
||||||
|
function localDay(instant: string | undefined): string | undefined {
|
||||||
|
return instant
|
||||||
|
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
|
||||||
|
if (!value) return undefined;
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(value);
|
||||||
|
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||||
|
? (parsed as Record<string, unknown>)
|
||||||
|
: undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-paciente',
|
selector: 'app-paciente',
|
||||||
imports: [
|
imports: [
|
||||||
@@ -81,7 +111,7 @@ function facts(observations: Observation[]): Fact[] {
|
|||||||
RouterLink,
|
RouterLink,
|
||||||
Plot,
|
Plot,
|
||||||
RiskScales,
|
RiskScales,
|
||||||
ReferenceRisk,
|
RiskSeries,
|
||||||
Stages,
|
Stages,
|
||||||
],
|
],
|
||||||
templateUrl: './paciente.html',
|
templateUrl: './paciente.html',
|
||||||
@@ -148,14 +178,20 @@ export class Paciente {
|
|||||||
});
|
});
|
||||||
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
|
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
|
||||||
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
|
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
|
||||||
|
/** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
|
||||||
|
* hysterectomy of her record is still held against her when the backend does not report it,
|
||||||
|
* as with evidence loaded without the day it was available. */
|
||||||
protected readonly riskExclusion = computed(() => {
|
protected readonly riskExclusion = computed(() => {
|
||||||
if (this.domain() !== 'cacu') return undefined;
|
if (this.domain() !== 'cacu') return undefined;
|
||||||
const patient = this.patient();
|
const patient = this.patient();
|
||||||
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
|
|
||||||
const sample = this.citologia()?.slice(0, 10);
|
const sample = this.citologia()?.slice(0, 10);
|
||||||
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
|
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
|
||||||
|
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
|
||||||
|
const reported = ineligibility(this.eligibility(), status, index);
|
||||||
|
if (reported) return reported;
|
||||||
|
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
|
||||||
return recorded && recorded <= index
|
return recorded && recorded <= index
|
||||||
? `Sin estimación de riesgo por antecedente de histerectomía registrado el ${recorded}.`
|
? `No disponible por: histerectomía registrada el ${recorded}.`
|
||||||
: undefined;
|
: undefined;
|
||||||
});
|
});
|
||||||
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
|
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
|
||||||
@@ -167,41 +203,91 @@ export class Paciente {
|
|||||||
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
|
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
|
||||||
});
|
});
|
||||||
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
|
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
|
||||||
protected readonly riskModels = computed(() => this.models().filter((m) => isRiskModel(m.model)));
|
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
|
||||||
protected readonly scales = computed(() =>
|
protected readonly scales = computed(() =>
|
||||||
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
|
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
|
||||||
);
|
);
|
||||||
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */
|
/** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
|
||||||
|
* survival only there is nothing to draw here: its scales are in the survival section. */
|
||||||
protected readonly groups = computed(() =>
|
protected readonly groups = computed(() =>
|
||||||
this.domain() === 'cacu' ? riskGroups(this.riskModels()) : [],
|
this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
|
||||||
|
? riskGroups(this.riskModels())
|
||||||
|
: [],
|
||||||
);
|
);
|
||||||
/** CaCu, experimental: the NCI reference comparison of the cytology she was opened at. The API
|
protected readonly survivalScales = computed(() =>
|
||||||
* answers 404 while the feature is off: then nothing is shown. */
|
this.domain() === 'cacu'
|
||||||
protected readonly reference = resource({
|
? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
|
||||||
|
: [],
|
||||||
|
);
|
||||||
|
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
|
||||||
|
* the model version that scored her. */
|
||||||
|
protected readonly combination = resource({
|
||||||
|
params: () => {
|
||||||
|
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
|
||||||
|
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
|
||||||
|
},
|
||||||
|
loader: async ({ params: { version, inputs } }) => {
|
||||||
|
const report = await this.api.invoke(readReport$Json, {
|
||||||
|
domain: 'cacu' as Domain,
|
||||||
|
name: 'survival',
|
||||||
|
version,
|
||||||
|
report: 'interpretability',
|
||||||
|
});
|
||||||
|
const found = combinationOf(report as Record<string, unknown>, inputs);
|
||||||
|
return found?.km
|
||||||
|
? { n: found.n, fallecidos: found.fallecidos, figure: combinationFigure(found.km) }
|
||||||
|
: { missing: noCurveText(report as Record<string, unknown>, found) };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
/** CaCu, experimental: the series her record can compare; none while the API has it off. */
|
||||||
|
protected readonly riskSeries = resource({
|
||||||
params: () =>
|
params: () =>
|
||||||
this.domain() === 'cacu'
|
this.domain() === 'cacu'
|
||||||
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
|
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
|
||||||
: undefined,
|
: undefined,
|
||||||
loader: async ({ params }): Promise<ReferenceView | undefined> => {
|
loader: async ({ params }): Promise<Series[] | undefined> => {
|
||||||
try {
|
try {
|
||||||
const answer = await firstValueFrom(
|
const answer = await firstValueFrom(
|
||||||
this.http.get<FhirParameters>(
|
this.http.get<FhirParameters>(
|
||||||
`${this.root}/cacu/fhir/Patient/${params.id}/$reference-risk`,
|
`${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
|
||||||
{
|
{
|
||||||
params: Object.fromEntries(
|
params: Object.fromEntries(
|
||||||
Object.entries({ cutoff: params.cutoff, sample: params.sample }).filter(
|
Object.entries({
|
||||||
([, v]) => !!v,
|
cutoff: params.cutoff,
|
||||||
|
sample: params.sample?.slice(0, 10),
|
||||||
|
}).filter((e): e is [string, string] => !!e[1]),
|
||||||
),
|
),
|
||||||
) as Record<string, string>,
|
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
return referenceView(answer);
|
return parseSeries(answer);
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
/** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a
|
||||||
|
* state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */
|
||||||
|
private readonly eligibilityData = resource({
|
||||||
|
params: () => (this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined),
|
||||||
|
loader: async ({ params }): Promise<EligibilityState> => {
|
||||||
|
try {
|
||||||
|
const answer = await this.api.invoke(cacuEligibility, {
|
||||||
|
domain: 'cacu' as Domain,
|
||||||
|
id: params.id,
|
||||||
|
cutoff: params.cutoff,
|
||||||
|
});
|
||||||
|
return eligibilityView(answer as FhirParameters);
|
||||||
|
} catch (error) {
|
||||||
|
return eligibilityFailure(error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
protected readonly eligibility = computed<EligibilityState>(() =>
|
||||||
|
this.eligibilityData.isLoading()
|
||||||
|
? { kind: 'loading' }
|
||||||
|
: (this.eligibilityData.value() ?? { kind: 'loading' }),
|
||||||
|
);
|
||||||
protected readonly saving = signal(false);
|
protected readonly saving = signal(false);
|
||||||
protected readonly saveError = signal('');
|
protected readonly saveError = signal('');
|
||||||
/** CaCu: her record as a PDF. */
|
/** CaCu: her record as a PDF. */
|
||||||
@@ -238,14 +324,15 @@ export class Paciente {
|
|||||||
protected readonly tests = computed(() => {
|
protected readonly tests = computed(() => {
|
||||||
const d = this.data.value();
|
const d = this.data.value();
|
||||||
if (!d) return [];
|
if (!d) return [];
|
||||||
return d.reports.map((r) => {
|
return d.reports.flatMap((r) => {
|
||||||
const results = (r.result ?? [])
|
const results = (r.result ?? [])
|
||||||
.map((x) => d.observations.get(x.reference?.split('/')[1]))
|
.map((x) => d.observations.get(x.reference?.split('/')[1]))
|
||||||
.filter((o) => !!o) as Observation[];
|
.filter((o) => !!o) as Observation[];
|
||||||
// the study's own results; the form's antecedents are in their own section and the extra
|
// the study's own results; the form's antecedents are in their own section and the extra
|
||||||
// findings are collapsed (record-groups)
|
// findings are collapsed (record-groups)
|
||||||
const found = group(facts(results));
|
const { hpv, rest } = hpvApart(facts(results));
|
||||||
return {
|
const found = group(rest);
|
||||||
|
const row = {
|
||||||
date: r.effectiveDateTime ?? '',
|
date: r.effectiveDateTime ?? '',
|
||||||
reported: ext(r, 'report-date')?.valueDate,
|
reported: ext(r, 'report-date')?.valueDate,
|
||||||
kind: label(r.code),
|
kind: label(r.code),
|
||||||
@@ -253,6 +340,10 @@ export class Paciente {
|
|||||||
results: found.results,
|
results: found.results,
|
||||||
findings: found.findings,
|
findings: found.findings,
|
||||||
};
|
};
|
||||||
|
// an HPV result is a study of its own: its own row, only when there is one
|
||||||
|
return hpv.length
|
||||||
|
? [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]
|
||||||
|
: [row];
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
|
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
|
||||||
@@ -298,6 +389,9 @@ export class Paciente {
|
|||||||
text: r.method?.text ?? '',
|
text: r.method?.text ?? '',
|
||||||
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
|
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
|
||||||
index: r.occurrenceDateTime ?? '',
|
index: r.occurrenceDateTime ?? '',
|
||||||
|
measure: ext(r, 'prediction-measure')?.valueCode,
|
||||||
|
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
|
||||||
|
evaluated: localDay(r.meta?.lastUpdated),
|
||||||
// the clinical scenarios of the model's report she falls in
|
// the clinical scenarios of the model's report she falls in
|
||||||
scenarios: (r.extension ?? [])
|
scenarios: (r.extension ?? [])
|
||||||
.filter((e) => e.url === EXT + 'escenario-clinico')
|
.filter((e) => e.url === EXT + 'escenario-clinico')
|
||||||
@@ -347,6 +441,10 @@ export class Paciente {
|
|||||||
return {
|
return {
|
||||||
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
|
factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[],
|
||||||
scenarios: m.scenarios,
|
scenarios: m.scenarios,
|
||||||
|
unavailable: [] as string[],
|
||||||
|
insufficient: [] as Insufficient[],
|
||||||
|
missing: [] as string[],
|
||||||
|
methods: [] as string[],
|
||||||
figures: mine(r['escenarios'] ?? []).map((e) =>
|
figures: mine(r['escenarios'] ?? []).map((e) =>
|
||||||
scenarioFigure(
|
scenarioFigure(
|
||||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
|
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`,
|
||||||
@@ -357,17 +455,29 @@ export class Paciente {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return {
|
const drawn = mine((report?.['escenarios'] ?? []) as any[]);
|
||||||
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
|
const figures = drawn.map((e) =>
|
||||||
scenarios: m.scenarios,
|
|
||||||
figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) =>
|
|
||||||
scenarioFigure(
|
scenarioFigure(
|
||||||
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
|
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
|
||||||
e,
|
e,
|
||||||
e.horizons_months,
|
e.horizons_months,
|
||||||
'Supervivencia S(t)',
|
'Supervivencia S(t)',
|
||||||
),
|
),
|
||||||
),
|
);
|
||||||
|
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
|
||||||
|
// CaCu: the report says which scenarios lack deaths (`escenarios_sin_curvas`); one it does not
|
||||||
|
// mention is not "insufficient", it is absent from the report. Other domains keep one list.
|
||||||
|
const { insufficient, missing } =
|
||||||
|
domain === 'cacu' ? sortUndrawn(report, undrawn) : { insufficient: [], missing: [] };
|
||||||
|
return {
|
||||||
|
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
|
||||||
|
scenarios: m.scenarios,
|
||||||
|
figures,
|
||||||
|
// her scenarios the report draws no curve for
|
||||||
|
unavailable: domain === 'cacu' ? [] : undrawn,
|
||||||
|
insufficient,
|
||||||
|
missing,
|
||||||
|
methods: methods(figures),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -482,10 +592,13 @@ export class Paciente {
|
|||||||
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
|
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
|
||||||
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
|
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
|
||||||
protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
|
protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
|
||||||
protected readonly curveText = computed(() => curveText(this.riskModels()));
|
|
||||||
private top(): number {
|
private top(): number {
|
||||||
return Math.max(0, ...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
|
return Math.max(
|
||||||
|
0,
|
||||||
|
...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
protected readonly insufficientText = insufficientText;
|
||||||
protected readonly name = name;
|
protected readonly name = name;
|
||||||
protected readonly levelNames = LEVEL_NAMES;
|
protected readonly levelNames = LEVEL_NAMES;
|
||||||
protected readonly identity = computed(() => {
|
protected readonly identity = computed(() => {
|
||||||
|
|||||||
@@ -46,3 +46,11 @@ export function group(facts: Fact[]) {
|
|||||||
}
|
}
|
||||||
return { antecedents, results, findings };
|
return { antecedents, results, findings };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const HPV_FIELDS = ['hpv', 'hpv_16', 'hpv_18'];
|
||||||
|
|
||||||
|
/** The cytology report's HPV results, apart from the cytology's own facts. */
|
||||||
|
export function hpvApart(facts: Fact[]) {
|
||||||
|
const isHpv = (f: Fact) => f.study === 'cervical_cytology' && HPV_FIELDS.includes(f.field);
|
||||||
|
return { hpv: facts.filter(isHpv), rest: facts.filter((f) => !isHpv(f)) };
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales';
|
import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
|
||||||
|
|
||||||
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
|
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ describe('the risk scales', () => {
|
|||||||
{ text: 'Recurrencia v2', index: '2026-03-01', predictions: [at(5, 0.98)] },
|
{ 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
|
{ 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.title)).toEqual(['Supervivencia', 'Recurrencia', 'Otro']);
|
||||||
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
|
expect(groups.map((g) => g.index)).toEqual(['2026-02-01', '2026-03-01', '2026-03-02']);
|
||||||
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años'];
|
const labels = ['Riesgo inmediato (al índice)', 'Riesgo a 5 años'];
|
||||||
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
|
for (const g of groups) expect(g.scales.map((s) => s.label)).toEqual(labels);
|
||||||
@@ -84,3 +84,21 @@ describe('which models feed the risk scales', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('survival scales', () => {
|
||||||
|
it('complements mortality and reverses interval bounds at every published horizon', () => {
|
||||||
|
const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
|
||||||
|
expect(g.survival).toBe(true);
|
||||||
|
expect(g.index).toBe('2026-01-01');
|
||||||
|
expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
|
||||||
|
expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
|
||||||
|
expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
|
||||||
|
});
|
||||||
|
it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
|
||||||
|
const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
|
||||||
|
expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
|
||||||
|
.toEqual(inputs);
|
||||||
|
expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
|
||||||
|
.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+181
-11
@@ -46,24 +46,89 @@ export function horizon(predictions: Prediction[], years: number): Prediction |
|
|||||||
export interface RiskGroup {
|
export interface RiskGroup {
|
||||||
/** the model's own title and the day it was scored (none: no model has scored her) */
|
/** the model's own title and the day it was scored (none: no model has scored her) */
|
||||||
title?: string;
|
title?: string;
|
||||||
|
scenario?: string;
|
||||||
index?: string;
|
index?: string;
|
||||||
|
survival?: boolean;
|
||||||
|
inputs?: Record<string, unknown>;
|
||||||
|
/** the model and version that scored her, and the day it did */
|
||||||
|
model?: string;
|
||||||
|
evaluated?: string;
|
||||||
scales: { label: string; risk?: Prediction }[];
|
scales: { label: string; risk?: Prediction }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
|
||||||
|
export function survivalGroups(
|
||||||
|
models: {
|
||||||
|
index: string;
|
||||||
|
predictions: Prediction[];
|
||||||
|
scenarios?: string[];
|
||||||
|
inputs?: Record<string, unknown>;
|
||||||
|
text?: string;
|
||||||
|
evaluated?: string;
|
||||||
|
}[],
|
||||||
|
): RiskGroup[] {
|
||||||
|
return models
|
||||||
|
.map((m) => ({
|
||||||
|
title: 'Supervivencia',
|
||||||
|
index: m.index,
|
||||||
|
survival: true,
|
||||||
|
inputs: m.inputs,
|
||||||
|
model: m.text,
|
||||||
|
evaluated: m.evaluated,
|
||||||
|
scenario: m.scenarios?.join(' · '),
|
||||||
|
scales: m.predictions.flatMap((p) => {
|
||||||
|
const v = horizon(m.predictions, p.years);
|
||||||
|
return v
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
|
||||||
|
risk: {
|
||||||
|
years: p.years,
|
||||||
|
p: 1 - v.p,
|
||||||
|
low: v.high === undefined ? undefined : 1 - v.high,
|
||||||
|
high: v.low === undefined ? undefined : 1 - v.low,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
.filter((g) => g.scales.length);
|
||||||
|
}
|
||||||
|
|
||||||
const HORIZONS: [number, string][] = [
|
const HORIZONS: [number, string][] = [
|
||||||
[0, 'Riesgo inmediato (al índice)'],
|
[0, 'Riesgo inmediato (al índice)'],
|
||||||
[5, 'Riesgo a 5 años'],
|
[5, 'Riesgo a 5 años'],
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/** A model's published title, "Riesgo de X en <escenario> v1", as its outcome and its scenario. */
|
||||||
|
export function titleParts(text: string): { title: string; scenario?: string } {
|
||||||
|
const [, title, scenario] = /^(.*?)(?: en (.+?))?(?: v\d+)?$/.exec(text)!;
|
||||||
|
return { title, scenario };
|
||||||
|
}
|
||||||
|
|
||||||
/** The scales the page draws: both horizons of every model, or, with no model, both horizons
|
/** The scales the page draws: both horizons of every model, or, with no model, both horizons
|
||||||
* unavailable. */
|
* unavailable. */
|
||||||
export function riskGroups(
|
export function riskGroups(
|
||||||
models: { text: string; index: string; predictions: Prediction[] }[],
|
models: {
|
||||||
|
text: string;
|
||||||
|
index: string;
|
||||||
|
predictions: Prediction[];
|
||||||
|
inputs?: Record<string, unknown>;
|
||||||
|
evaluated?: string;
|
||||||
|
}[],
|
||||||
): RiskGroup[] {
|
): RiskGroup[] {
|
||||||
const scales = (predictions: Prediction[]) =>
|
const scales = (predictions: Prediction[]) =>
|
||||||
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
|
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
|
||||||
return models.length
|
return models.length
|
||||||
? models.map((m) => ({ title: m.text, index: m.index, scales: scales(m.predictions) }))
|
? models.map((m) => ({
|
||||||
|
...titleParts(m.text),
|
||||||
|
index: m.index,
|
||||||
|
inputs: m.inputs,
|
||||||
|
model: m.text,
|
||||||
|
evaluated: m.evaluated,
|
||||||
|
scales: scales(m.predictions),
|
||||||
|
}))
|
||||||
: [{ scales: scales([]) }];
|
: [{ scales: scales([]) }];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,12 +139,9 @@ export function riskGroups(
|
|||||||
selector: 'app-risk-scales',
|
selector: 'app-risk-scales',
|
||||||
imports: [DecimalPipe],
|
imports: [DecimalPipe],
|
||||||
template: `
|
template: `
|
||||||
@if (groups().length) {
|
|
||||||
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
|
|
||||||
}
|
|
||||||
@for (g of groups(); track $index) {
|
@for (g of groups(); track $index) {
|
||||||
@if (g.title) {
|
@if (g.title) {
|
||||||
<h3>{{ g.title }}{{ g.index ? ' · fecha índice ' + g.index : '' }}</h3>
|
<h3>{{ g.title }}</h3>
|
||||||
}
|
}
|
||||||
@for (s of g.scales; track s.label) {
|
@for (s of g.scales; track s.label) {
|
||||||
<div class="risk-scale" [attr.data-scale]="s.label">
|
<div class="risk-scale" [attr.data-scale]="s.label">
|
||||||
@@ -94,9 +156,17 @@ export function riskGroups(
|
|||||||
· No disponible
|
· No disponible
|
||||||
}
|
}
|
||||||
</p>
|
</p>
|
||||||
<div class="risk-plot" [class.unavailable]="!s.risk">
|
<div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
|
||||||
<div class="risk-line" aria-hidden="true"></div>
|
<div class="risk-line" aria-hidden="true"></div>
|
||||||
@if (s.risk; as r) {
|
@if (s.risk; as r) {
|
||||||
|
@if (r.low !== undefined && r.high !== undefined) {
|
||||||
|
<span
|
||||||
|
class="risk-interval"
|
||||||
|
[style.left.%]="r.low * 100"
|
||||||
|
[style.width.%]="(r.high - r.low) * 100"
|
||||||
|
aria-hidden="true"
|
||||||
|
></span>
|
||||||
|
}
|
||||||
<span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
|
<span class="risk-marker" [style.left.%]="r.p * 100" aria-hidden="true"></span>
|
||||||
<strong
|
<strong
|
||||||
class="risk-value"
|
class="risk-value"
|
||||||
@@ -110,12 +180,60 @@ export function riskGroups(
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
@if (g.index) {
|
||||||
|
<p class="muted foot">
|
||||||
|
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
@if (g.title && !g.survival) {
|
||||||
|
<section>
|
||||||
|
<h4>Factores de riesgo considerados</h4>
|
||||||
|
@if (g.inputs) {
|
||||||
|
<dl>
|
||||||
|
@for (item of entries(g.inputs); track item[0]) {
|
||||||
|
<div>
|
||||||
|
<dt>{{ inputName(item[0]) }}</dt>
|
||||||
|
<dd>{{ inputValue(item[0], item[1]) }}</dd>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
} @else {
|
||||||
|
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
@if (g.model) {
|
||||||
|
<details data-section="metodos">
|
||||||
|
<summary>Métodos</summary>
|
||||||
|
<dl>
|
||||||
|
<div>
|
||||||
|
<dt>Modelo y versión</dt>
|
||||||
|
<dd>{{ g.model }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Fecha índice</dt>
|
||||||
|
<dd>{{ g.index }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Fecha de evaluación</dt>
|
||||||
|
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Covariables</dt>
|
||||||
|
<dd>
|
||||||
|
@for (item of entries(g.inputs ?? {}); track item[0]) {
|
||||||
|
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
|
||||||
|
} @empty {
|
||||||
|
No disponibles para esta estimación.
|
||||||
|
}
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
.note {
|
|
||||||
margin: 0 0 8px;
|
|
||||||
}
|
|
||||||
.risk-scale {
|
.risk-scale {
|
||||||
margin: 8px 0 14px;
|
margin: 8px 0 14px;
|
||||||
max-width: 740px;
|
max-width: 740px;
|
||||||
@@ -124,7 +242,7 @@ export function riskGroups(
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
.risk-plot {
|
.risk-plot {
|
||||||
padding-top: 24px;
|
padding-top: 30px;
|
||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
.risk-line {
|
.risk-line {
|
||||||
@@ -146,6 +264,35 @@ export function riskGroups(
|
|||||||
#fff 25%
|
#fff 25%
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
.survival .risk-line {
|
||||||
|
background: linear-gradient(
|
||||||
|
to right,
|
||||||
|
#c24269 0 25%,
|
||||||
|
#df8640 25% 50%,
|
||||||
|
#a8c243 50% 75%,
|
||||||
|
#42a77e 75% 100%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
.risk-interval {
|
||||||
|
border-left: 2px solid #17324d;
|
||||||
|
border-right: 2px solid #17324d;
|
||||||
|
height: 8px;
|
||||||
|
min-width: 2px;
|
||||||
|
position: absolute;
|
||||||
|
top: 20px;
|
||||||
|
}
|
||||||
|
.risk-interval::before {
|
||||||
|
background: #17324d;
|
||||||
|
content: '';
|
||||||
|
height: 2px;
|
||||||
|
left: 0;
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
top: 3px;
|
||||||
|
}
|
||||||
|
.foot {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
.risk-marker {
|
.risk-marker {
|
||||||
background: #17324d;
|
background: #17324d;
|
||||||
bottom: -2px;
|
bottom: -2px;
|
||||||
@@ -172,4 +319,27 @@ export function riskGroups(
|
|||||||
})
|
})
|
||||||
export class RiskScales {
|
export class RiskScales {
|
||||||
readonly groups = input.required<RiskGroup[]>();
|
readonly groups = input.required<RiskGroup[]>();
|
||||||
|
protected readonly entries = Object.entries;
|
||||||
|
protected readonly inputName = (name: string) =>
|
||||||
|
(
|
||||||
|
({
|
||||||
|
age_group: 'Edad al diagnóstico',
|
||||||
|
cytology: 'Citología',
|
||||||
|
hpv: 'VPH',
|
||||||
|
hpv_positive: 'VPH',
|
||||||
|
hpv_16_18: 'VPH 16/18',
|
||||||
|
referral_grade: 'Referencia',
|
||||||
|
bethesda: 'Citología',
|
||||||
|
hpv_16: 'VPH 16',
|
||||||
|
hpv_18: 'VPH 18',
|
||||||
|
}) as Record<string, string>
|
||||||
|
)[name] ?? name;
|
||||||
|
protected readonly inputValue = (name: string, value: unknown) => {
|
||||||
|
if (value === null || value === undefined) return 'No documentado';
|
||||||
|
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
|
||||||
|
return value ? 'Positivo' : 'Negativo';
|
||||||
|
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
|
||||||
|
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
|
||||||
|
return String(value);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { parseSeries, seriesName } from './risk-series';
|
||||||
|
|
||||||
|
describe('risk series', () => {
|
||||||
|
it('reads each series and keeps an absent interval absent', () => {
|
||||||
|
const [series] = parseSeries({
|
||||||
|
resourceType: 'Parameters',
|
||||||
|
parameter: [
|
||||||
|
{
|
||||||
|
name: 'series',
|
||||||
|
part: [
|
||||||
|
{ name: 'id', valueString: 'cacu.cin2_pim' },
|
||||||
|
{ name: 'source', valueString: 'Institucional' },
|
||||||
|
{ name: 'outcome', valueString: 'CIN2+' },
|
||||||
|
{ name: 'status', valueCode: 'resolved' },
|
||||||
|
{
|
||||||
|
name: 'point',
|
||||||
|
part: [
|
||||||
|
{ name: 'years', valueInteger: 0 },
|
||||||
|
{ name: 'probability', valueDecimal: 0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
|
||||||
|
expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
|
||||||
|
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
|
||||||
|
'NCI, ingreso a LIEAG+',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { Component, computed, input, signal } from '@angular/core';
|
||||||
|
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||||
|
import type { Parameters, ParametersParameter } from 'fhir/r4';
|
||||||
|
import { Plot } from '../plot';
|
||||||
|
import { curveFigure } from './risk-curve';
|
||||||
|
|
||||||
|
export interface SeriesPoint {
|
||||||
|
years: number;
|
||||||
|
p: number;
|
||||||
|
low?: number;
|
||||||
|
high?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One series of `$risk-series`: a source, an outcome and her variables. */
|
||||||
|
export interface Series {
|
||||||
|
id: string;
|
||||||
|
source: string;
|
||||||
|
outcome: string;
|
||||||
|
label: string;
|
||||||
|
resolved: boolean;
|
||||||
|
reasons: string[];
|
||||||
|
assumptions: string[];
|
||||||
|
points: SeriesPoint[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const OUTCOME_TEXT: Record<string, string> = {
|
||||||
|
'CIN2+': 'LIEAG+ (CIN2+)',
|
||||||
|
'CIN3+': 'CIN3+',
|
||||||
|
cancer: 'Cáncer',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const seriesName = (s: Series) => {
|
||||||
|
const outcome = OUTCOME_TEXT[s.outcome] ?? s.outcome;
|
||||||
|
if (s.source === 'NCI (tabla de ingreso)')
|
||||||
|
return `NCI, ingreso a ${outcome.replace(' (CIN2+)', '').replace(/^Cáncer$/, 'cáncer')}`;
|
||||||
|
// the platform's own models are the hospital's: its name, and the outcome without its synonym
|
||||||
|
return s.source === 'Institucional'
|
||||||
|
? `ISSSTELEON, ${outcome.replace(' (CIN2+)', '')}`
|
||||||
|
: `${s.source} · ${outcome}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The series of the answer. A value absent from it stays absent. */
|
||||||
|
export function parseSeries(answer: Parameters): Series[] {
|
||||||
|
const all = (parts: ParametersParameter[] | undefined, name: string) =>
|
||||||
|
(parts ?? []).filter((p) => p.name === name);
|
||||||
|
const one = (parts: ParametersParameter[] | undefined, name: string) => all(parts, name)[0];
|
||||||
|
return all(answer.parameter, 'series').map(({ part }) => ({
|
||||||
|
id: one(part, 'id')?.valueString ?? '',
|
||||||
|
source: one(part, 'source')?.valueString ?? '',
|
||||||
|
outcome: one(part, 'outcome')?.valueString ?? '',
|
||||||
|
label: one(part, 'label')?.valueString ?? '',
|
||||||
|
resolved: one(part, 'status')?.valueCode === 'resolved',
|
||||||
|
reasons: all(part, 'reason').map((r) => r.valueCode ?? ''),
|
||||||
|
assumptions: all(part, 'assumption').map((a) => a.valueString ?? ''),
|
||||||
|
points: all(part, 'point').map(({ part: at }) => ({
|
||||||
|
years: one(at, 'years')?.valueInteger ?? 0,
|
||||||
|
p: one(at, 'probability')?.valueDecimal ?? 0,
|
||||||
|
low: one(at, 'low')?.valueDecimal,
|
||||||
|
high: one(at, 'high')?.valueDecimal,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The chosen series as curves. Series are shown side by side; no difference is computed. */
|
||||||
|
@Component({
|
||||||
|
selector: 'app-risk-series',
|
||||||
|
imports: [MatCheckboxModule, Plot],
|
||||||
|
template: `
|
||||||
|
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
|
||||||
|
<div class="choices">
|
||||||
|
@for (s of available(); track s.id) {
|
||||||
|
<mat-checkbox [checked]="chosen().has(s.id)" (change)="toggle(s.id)">
|
||||||
|
{{ name(s) }}
|
||||||
|
</mat-checkbox>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (selected().length) {
|
||||||
|
@for (assumption of assumptions(); track assumption) {
|
||||||
|
<p class="muted">{{ assumption }}</p>
|
||||||
|
}
|
||||||
|
<app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
|
||||||
|
}
|
||||||
|
@if (!available().length) {
|
||||||
|
<p class="muted">No disponible: datos insuficientes.</p>
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
styles: `
|
||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.choices {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0 16px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class RiskSeries {
|
||||||
|
readonly series = input.required<Series[]>();
|
||||||
|
protected readonly name = seriesName;
|
||||||
|
protected readonly available = computed(() => this.series().filter((s) => s.points.length));
|
||||||
|
/** what the user toggled away from the default (the institutional series) */
|
||||||
|
private readonly toggled = signal(new Set<string>());
|
||||||
|
protected readonly chosen = computed(
|
||||||
|
() =>
|
||||||
|
new Set(
|
||||||
|
this.available()
|
||||||
|
.filter((s) => (s.source === 'Institucional') !== this.toggled().has(s.id))
|
||||||
|
.map((s) => s.id),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
protected readonly selected = computed(() =>
|
||||||
|
this.available().filter((s) => this.chosen().has(s.id)),
|
||||||
|
);
|
||||||
|
/** what the chosen series assume, each said once */
|
||||||
|
protected readonly assumptions = computed(() => [
|
||||||
|
...new Set(this.selected().flatMap((s) => s.assumptions)),
|
||||||
|
]);
|
||||||
|
protected readonly figure = computed(() => {
|
||||||
|
const shown = this.selected().map((s) => ({
|
||||||
|
model: s.id,
|
||||||
|
text: seriesName(s),
|
||||||
|
index: '',
|
||||||
|
predictions: s.points,
|
||||||
|
}));
|
||||||
|
const top = Math.max(...shown.flatMap((m) => m.predictions.map((p) => p.high ?? p.p)));
|
||||||
|
const figure = curveFigure(shown, top);
|
||||||
|
// sources do not share an index date: the axis says only the horizon
|
||||||
|
figure.layout!.xaxis!.title = { text: 'Horizonte (años)' };
|
||||||
|
return figure;
|
||||||
|
});
|
||||||
|
|
||||||
|
protected toggle(id: string) {
|
||||||
|
const next = new Set(this.toggled());
|
||||||
|
if (!next.delete(id)) next.add(id);
|
||||||
|
this.toggled.set(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -113,7 +113,7 @@ export function interval(from?: string, to?: string, inferred = false): string {
|
|||||||
<span>{{
|
<span>{{
|
||||||
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
|
s.day ?? (s.requested ? 'Solicitada el ' + s.requested : 'Sin fecha')
|
||||||
}}</span>
|
}}</span>
|
||||||
@if (s.origin) {
|
@if (s.origin && s.origin !== 'Formulario de citología') {
|
||||||
<span class="origin">Procedencia: {{ s.origin }}</span>
|
<span class="origin">Procedencia: {{ s.origin }}</span>
|
||||||
}
|
}
|
||||||
<span class="interval">Desde anterior: {{ s.previous }}</span>
|
<span class="interval">Desde anterior: {{ s.previous }}</span>
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { combinationOf, noCurveText } from './survival-combination';
|
||||||
|
|
||||||
|
describe('combinationOf', () => {
|
||||||
|
const values = { age_group: '<30', cytology: 'NA', hpv: 'positive' };
|
||||||
|
const report = { km_combinaciones: [{ valores: values, n: 9, fallecidos: 6 }] };
|
||||||
|
|
||||||
|
it('takes only the entry with all her values, a missing one as NA', () => {
|
||||||
|
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'positive' })?.n).toBe(9);
|
||||||
|
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'negative' })).toBe(
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
expect(combinationOf(report, { age_group: '<30' })).toBe(undefined);
|
||||||
|
expect(combinationOf({}, values)).toBe(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tells an old report apart from a combination with too few deaths', () => {
|
||||||
|
expect(noCurveText({}, undefined)).toContain('no publica esta curva');
|
||||||
|
expect(
|
||||||
|
noCurveText(
|
||||||
|
{ ...report, min_fallecidos_escenario: 5 },
|
||||||
|
{ valores: values, n: 9, fallecidos: 2 },
|
||||||
|
),
|
||||||
|
).toContain('n = 9, fallecidos = 2; mínimo requerido: 5');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { Figure, PALETTE } from '../plot';
|
||||||
|
|
||||||
|
/** One entry of the survival report's `km_combinaciones`: the patients who share every value. */
|
||||||
|
export interface Combination {
|
||||||
|
valores: Record<string, string>;
|
||||||
|
n: number;
|
||||||
|
fallecidos: number;
|
||||||
|
km?: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry with exactly her values (a missing one is the report's "NA"); never a partial match. */
|
||||||
|
export function combinationOf(
|
||||||
|
report: Record<string, unknown> | null | undefined,
|
||||||
|
inputs: Record<string, unknown>,
|
||||||
|
): Combination | undefined {
|
||||||
|
const all = report?.['km_combinaciones'];
|
||||||
|
return (Array.isArray(all) ? (all as Combination[]) : []).find((c) => {
|
||||||
|
const keys = Object.keys(c.valores);
|
||||||
|
return (
|
||||||
|
keys.length === Object.keys(inputs).length &&
|
||||||
|
keys.every((k) => k in inputs && c.valores[k] === String(inputs[k] ?? 'NA'))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Why there is no curve for her: these are not the same thing, so each is said apart. (A patient
|
||||||
|
* outside the survival scenario has no survival section at all.) */
|
||||||
|
export function noCurveText(
|
||||||
|
report: Record<string, unknown> | null | undefined,
|
||||||
|
found: Combination | undefined,
|
||||||
|
): string {
|
||||||
|
if (!Array.isArray(report?.['km_combinaciones']))
|
||||||
|
return 'No disponible: la versión del modelo que la evaluó no publica esta curva.';
|
||||||
|
const minimum = report['min_fallecidos_escenario'];
|
||||||
|
const counts = `n = ${found?.n ?? 0}, fallecidos = ${found?.fallecidos ?? 0}`;
|
||||||
|
return `No disponible: datos insuficientes para su combinación de valores (${counts}${
|
||||||
|
typeof minimum === 'number' ? `; mínimo requerido: ${minimum} fallecidos` : ''
|
||||||
|
}).`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function combinationFigure(km: NonNullable<Combination['km']>): Figure {
|
||||||
|
const line = (y: number[], more: object) => ({
|
||||||
|
type: 'scatter',
|
||||||
|
mode: 'lines',
|
||||||
|
x: km.months,
|
||||||
|
y,
|
||||||
|
line: { shape: 'hv', color: PALETTE[0], width: 0 },
|
||||||
|
...more,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
data: [
|
||||||
|
line(km.low, { showlegend: false, hoverinfo: 'skip' }),
|
||||||
|
line(km.high, { name: 'IC 95 %', fill: 'tonexty', fillcolor: 'rgba(23, 50, 77, 0.15)' }),
|
||||||
|
line(km.S, { name: 'Kaplan-Meier', line: { shape: 'hv', color: PALETTE[0], width: 2 } }),
|
||||||
|
],
|
||||||
|
layout: {
|
||||||
|
xaxis: { title: { text: 'Meses desde el índice' } },
|
||||||
|
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [0, 1.02], tickformat: '.0%' },
|
||||||
|
},
|
||||||
|
} as Figure;
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import { scenarioFigure } from '../gobernanza/figures';
|
||||||
|
import { insufficientText, sortUndrawn } from './survival-scenarios';
|
||||||
|
|
||||||
|
const base = (over: object = {}) => ({
|
||||||
|
km: {
|
||||||
|
months: [0, 12, 24, 36],
|
||||||
|
S: [1, 0.9, 0.8, 0.7],
|
||||||
|
low: [1, 0.8, 0.7, 0.55],
|
||||||
|
high: [1, 0.95, 0.9, 0.82],
|
||||||
|
},
|
||||||
|
weibull: { t: [0, 36], S: [1, 0.7] },
|
||||||
|
weibull_fractional: { t: [0, 36], S: [1, 0.72] },
|
||||||
|
points: { COMB: { S: [0.9, 0.7], low: [0.8, 0.55], high: [0.95, 0.82] } },
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
const draw = (e: object) => scenarioFigure('t', e, [12, 36], 'S(t)').figure.data as any[];
|
||||||
|
const bands = (d: any[]) => d.filter((t) => t.fill === 'toself');
|
||||||
|
const model = (d: any[]) => d.find((t) => t.name?.startsWith('LR + HBN'));
|
||||||
|
|
||||||
|
describe('survival curves with absent values', () => {
|
||||||
|
it('complete data draw one band and symmetric-free error bars, as before', () => {
|
||||||
|
const d = draw(base());
|
||||||
|
expect(bands(d).length).toBe(1);
|
||||||
|
expect(bands(d)[0].x.length).toBe(8);
|
||||||
|
expect(model(d).error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.05, 0.12]);
|
||||||
|
expect(model(d).error_y.arrayminus.map((v: number) => +v.toFixed(2))).toEqual([0.1, 0.15]);
|
||||||
|
});
|
||||||
|
it('a band is drawn only where both limits exist, never from an absent one', () => {
|
||||||
|
const km = {
|
||||||
|
months: [0, 12, 24, 36, 48],
|
||||||
|
S: [1, 0.9, 0.8, 0.7, 0.6],
|
||||||
|
low: [1, 0.8, null, 0.55, 0.4],
|
||||||
|
high: [1, 0.95, null, 0.82, 0.7],
|
||||||
|
};
|
||||||
|
const d = draw(base({ km }));
|
||||||
|
expect(bands(d).map((b) => b.x.length)).toEqual([4, 4]); // [0,12] and [36,48]; each polygon out and back
|
||||||
|
for (const b of bands(d)) expect(b.y.every((v: unknown) => typeof v === 'number')).toBe(true);
|
||||||
|
const none = draw(
|
||||||
|
base({
|
||||||
|
km: { ...km, low: [null, null, null, null, null], high: [null, null, null, null, null] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(bands(none).length).toBe(0); // no limits: no band at all
|
||||||
|
expect(none.find((t) => t.name?.startsWith('Kaplan')).y).toEqual([1, 0.9, 0.8, 0.7, 0.6]); // the curve stays
|
||||||
|
});
|
||||||
|
it('a point without its limits has no bar; zero is a value and unavailable is not drawn', () => {
|
||||||
|
const d = draw(
|
||||||
|
base({ points: { COMB: { S: [0, null], low: [null, null], high: [null, null] } } }),
|
||||||
|
);
|
||||||
|
const m = model(d);
|
||||||
|
expect(m.y).toEqual([0, null]); // 0 % is drawn at 0, an absent value is a gap
|
||||||
|
expect(m.error_y).toBeUndefined(); // no invented limits
|
||||||
|
expect(model(draw(base({ points: { COMB: { S: [0, null] } } }))).error_y).toBeUndefined();
|
||||||
|
const half = model(
|
||||||
|
draw(base({ points: { COMB: { S: [0.9, 0.7], low: [0.8, null], high: [0.95, null] } } })),
|
||||||
|
);
|
||||||
|
expect(half.error_y.array).toEqual([expect.closeTo(0.05, 5), null]);
|
||||||
|
expect(half.error_y.arrayminus).toEqual([expect.closeTo(0.1, 5), null]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('scenarios without a curve', () => {
|
||||||
|
const report = {
|
||||||
|
escenarios_sin_curvas: [
|
||||||
|
{ escenario: 'VPH negativo', n: 9, fallecidos: 2 },
|
||||||
|
{ escenario: 'Citología · ASC-H', n: 0, fallecidos: 0 },
|
||||||
|
],
|
||||||
|
min_fallecidos_escenario: 5,
|
||||||
|
};
|
||||||
|
it('those the report lists as lacking deaths keep its numbers and the minimum', () => {
|
||||||
|
expect(sortUndrawn(report, ['VPH negativo', 'Citología · ASC-H']).insufficient).toEqual([
|
||||||
|
{ name: 'VPH negativo', n: 9, deaths: 2, minimum: 5 },
|
||||||
|
{ name: 'Citología · ASC-H', n: 0, deaths: 0, minimum: 5 }, // zero deaths is a count, not a gap
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
it('one the report does not mention is absent, never "insufficient"', () => {
|
||||||
|
expect(sortUndrawn(report, ['VPH negativo', 'Edad · 45-54']).missing).toEqual(['Edad · 45-54']);
|
||||||
|
expect(sortUndrawn({}, ['a'])).toEqual({ insufficient: [], missing: ['a'] });
|
||||||
|
expect(sortUndrawn(null, ['a'])).toEqual({ insufficient: [], missing: ['a'] });
|
||||||
|
expect(sortUndrawn({ escenarios_sin_curvas: 'x' }, ['a']).missing).toEqual(['a']);
|
||||||
|
});
|
||||||
|
it('a listing without counts is still insufficient, without inventing numbers', () => {
|
||||||
|
expect(
|
||||||
|
sortUndrawn({ escenarios_sin_curvas: [{ escenario: 'a' }] }, ['a']).insufficient,
|
||||||
|
).toEqual([{ name: 'a', n: undefined, deaths: undefined, minimum: undefined }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the insufficient-data text', () => {
|
||||||
|
it("says the report's numbers and leaves out the ones it did not give", () => {
|
||||||
|
expect(insufficientText({ name: 'a', n: 9, deaths: 2, minimum: 5 })).toBe(
|
||||||
|
'Datos insuficientes para trazar la curva (n = 9, fallecidos = 2; mínimo requerido: 5 fallecidos).',
|
||||||
|
);
|
||||||
|
expect(insufficientText({ name: 'a', n: 0, deaths: 0 })).toBe(
|
||||||
|
'Datos insuficientes para trazar la curva (n = 0, fallecidos = 0).',
|
||||||
|
);
|
||||||
|
expect(insufficientText({ name: 'a', n: null, deaths: 0, minimum: 5 })).toBe(
|
||||||
|
'Datos insuficientes para trazar la curva (fallecidos = 0; mínimo requerido: 5 fallecidos).',
|
||||||
|
);
|
||||||
|
expect(insufficientText({ name: 'a' })).toBe('Datos insuficientes para trazar la curva.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/** A scenario the report says has too few deaths for a curve, with its counts and the minimum. */
|
||||||
|
export interface Insufficient {
|
||||||
|
name: string;
|
||||||
|
n?: number | null;
|
||||||
|
deaths?: number | null;
|
||||||
|
minimum?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Her scenarios without a curve, apart: those the report lists as lacking deaths (with the numbers it
|
||||||
|
* gives) and those it does not mention at all. */
|
||||||
|
export function sortUndrawn(
|
||||||
|
report: Record<string, unknown> | null | undefined,
|
||||||
|
undrawn: string[],
|
||||||
|
): { insufficient: Insufficient[]; missing: string[] } {
|
||||||
|
const listed = (
|
||||||
|
Array.isArray(report?.['escenarios_sin_curvas']) ? report['escenarios_sin_curvas'] : []
|
||||||
|
) as {
|
||||||
|
escenario?: string;
|
||||||
|
n?: number | null;
|
||||||
|
fallecidos?: number | null;
|
||||||
|
}[];
|
||||||
|
const minimum =
|
||||||
|
typeof report?.['min_fallecidos_escenario'] === 'number'
|
||||||
|
? report['min_fallecidos_escenario']
|
||||||
|
: undefined;
|
||||||
|
const insufficient: Insufficient[] = [];
|
||||||
|
const missing: string[] = [];
|
||||||
|
for (const name of undrawn) {
|
||||||
|
const found = listed.find((s) => s.escenario === name);
|
||||||
|
if (found) insufficient.push({ name, n: found.n, deaths: found.fallecidos, minimum });
|
||||||
|
else missing.push(name);
|
||||||
|
}
|
||||||
|
return { insufficient, missing };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the section says of a scenario the report lists as lacking deaths; the numbers are the
|
||||||
|
* report's and a missing one is left out, never replaced. */
|
||||||
|
export function insufficientText(u: Insufficient): string {
|
||||||
|
const fmt = (v: number) => v.toLocaleString('es-MX');
|
||||||
|
const counts = [
|
||||||
|
typeof u.n === 'number' ? `n = ${fmt(u.n)}` : '',
|
||||||
|
typeof u.deaths === 'number' ? `fallecidos = ${fmt(u.deaths)}` : '',
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ');
|
||||||
|
const details = [
|
||||||
|
counts,
|
||||||
|
u.minimum !== undefined ? `mínimo requerido: ${fmt(u.minimum)} fallecidos` : '',
|
||||||
|
].filter(Boolean);
|
||||||
|
return `Datos insuficientes para trazar la curva${details.length ? ` (${details.join('; ')})` : ''}.`;
|
||||||
|
}
|
||||||
+6
-1
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
|
|||||||
export class Plot implements OnDestroy {
|
export class Plot implements OnDestroy {
|
||||||
readonly figure = input.required<Figure>();
|
readonly figure = input.required<Figure>();
|
||||||
readonly height = input(320);
|
readonly height = input(320);
|
||||||
|
/** Plotly's buttons over the chart; a record's curves go without them */
|
||||||
|
readonly toolbar = input(true);
|
||||||
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
|
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
const { data, layout } = this.figure();
|
const { data, layout } = this.figure();
|
||||||
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG);
|
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
|
||||||
|
...CONFIG,
|
||||||
|
...(this.toolbar() ? {} : { displayModeBar: false }),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ type Entity = Rejection['entity'];
|
|||||||
type Row = Record<string, unknown>;
|
type Row = Record<string, unknown>;
|
||||||
|
|
||||||
const ENTITIES: Record<Entity, string> = {
|
const ENTITIES: Record<Entity, string> = {
|
||||||
|
cacu_eligibility_evidence: 'Evidencia de elegibilidad CaCu',
|
||||||
cervical_cytology: 'Citología cervical',
|
cervical_cytology: 'Citología cervical',
|
||||||
cervical_biopsy: 'Biopsia cervical',
|
cervical_biopsy: 'Biopsia cervical',
|
||||||
clinical_note: 'Nota médica',
|
clinical_note: 'Nota médica',
|
||||||
|
|||||||
Reference in New Issue
Block a user