diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index f024b4f..1e1d89c 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -73,7 +73,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie await expect(rows).toHaveCount(Math.min(20, bundle.total)); await expect(rows.first().locator('a').first()).toHaveText(first); await page.getByRole('button', { name: 'Siguiente' }).click(); - await expect(page.getByText(`21–`)).toBeVisible(); + await expect(page.getByText(/Página 2 de \d+, \d+ registros/)).toBeVisible(); await page.getByRole('button', { name: 'Anterior' }).click(); await rows.first().locator('a').first().click(); @@ -198,10 +198,54 @@ function captured(domain: string) { const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs; const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad'); - return items + const old = items .slice(from) .filter((i) => ['h2', 'h3', 'plot'].includes(i.kind)) .filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption + return domain === 'cacu' ? rearranged(old) : old; +} +/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the + * opportunity section, under its cards, and the cytology distribution is a table in the joint + * results card (its nested donut is not drawn any more). Nothing else of the old page moves. */ +function rearranged(old: any[]) { + const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje'); + const moved = old.splice(route, 2); // its heading and its plot + old.splice( + old.findIndex((i) => i.text === 'Indicadores clínicos'), + 0, + moved[0], + moved[1], + ); + // the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the + // cytology section, under another title) are not headings of this page any more + return old.filter( + (i) => + !/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test( + i.text ?? '', + ), + ); +} +/** Sections this platform adds to an old page, by domain, in the order they appear. The old + * headings still have to appear, in their order; nothing else may appear (a figure's own + * `h3.figure-title` inside a measure's card is the card's, not a section). */ +const ADDED: Record = { + cacu: [ + 'Resultados de citología, VPH y biopsia', + 'Resultados de VPH por genotipo', + 'Resultados de biopsia cervical', + 'Pacientes evaluadas por resultado de VPH (última muestra con resultado)', + 'VPP tras colposcopía registrada', + ], +}; +/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */ +function oldThenAdded(actual: string[], old: string[], added: string[]) { + const extra: string[] = []; + let found = 0; + for (const heading of actual) { + if (found < old.length && heading === old[found]) found++; + else extra.push(heading); + } + return { allOldInOrder: found === old.length, extra, added }; } const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', '); const kindOf = (types: string[]) => [...new Set(types)].sort().join('+'); @@ -215,13 +259,19 @@ for (const domain of ['cacu', 'cama', 'tea']) { const tab = page.locator('app-tab-indicadores'); await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); + // textContent: a heading inside a collapsed section (CaCu's original confirmation measure) + // is still a heading of the page, though the browser gives it no rendered text. const headings = await tab - .locator('h2, h3') - .evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim())); + .locator('h2, h3:not(.figure-title)') + .evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim())); const from = headings.indexOf('Indicadores de oportunidad'); - expect(headings.slice(from).map(period)).toEqual( + const seen = oldThenAdded( + headings.slice(from).map(period), old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)), + ADDED[domain] ?? [], ); + expect(seen.allOldInOrder).toBe(true); + expect(seen.extra).toEqual(seen.added); // Each figure drawn is one of the old kinds (a figure with no data in the period is named). const drawn = await tab .locator('.js-plotly-plot') @@ -291,6 +341,280 @@ for (const domain of ['cacu', 'cama', 'tea']) { }); } +test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({ + page, +}) => { + const asked: string[] = []; + page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url())); + await page.goto('/indicadores/cacu'); + const tab = page.locator('app-tab-indicadores'); + await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible(); + await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 }); + + // cumulative (the default), step by step with its warning and quartiles, and by ICD-10 + // the route's times are in the opportunity section, after its cards and before the clinical ones + const opportunity = tab.locator('section.opportunity'); + await expect(opportunity.locator('.route-card')).toBeVisible(); + await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0); + expect( + await opportunity.evaluate((el) => { + const kpis = el.querySelector('.kpis')!; + const card = el.querySelector('.route-card')!; + return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING); + }), + ).toBe(true); + await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible(); + await tab.getByRole('radio', { name: 'Por pasos' }).click(); + // by steps: independent bars from zero in a table, every step kept, and the medians not added + const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' }); + await expect(steps).toBeVisible(); + await expect(steps.locator('tbody tr')).toHaveCount(4); + await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible(); + await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0); + await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click(); + await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible(); + await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click(); + await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible(); + await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible(); + + // the sections of the new measures: each one in the place of its subject + for (const measure of [ + 'CACU_VPH_GENOTIPO', + 'CACU_VPH', + 'CACU_BIOPSIA_RESULTADOS', + 'CACU_VPP_COLPOSCOPIA', + ]) + await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible(); + // a PPV says what it is and what it is not + await expect( + tab + .locator('[data-measure="CACU_VPP_COLPOSCOPIA"]') + .getByText('no un vínculo clínico confirmado'), + ).toBeVisible(); + // the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut + const joint = tab.locator('.results-card'); + const [cyto, hpv, biopsy] = await Promise.all( + ['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) => + joint.locator(`section[data-measure="${m}"]`).boundingBox(), + ), + ); + expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2); + expect(cyto!.x).toBeLessThan(hpv!.x); + expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1); + expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8); + await expect( + joint.getByRole('table', { name: 'Distribución de resultados citológicos' }), + ).toBeVisible(); + await expect(joint.getByText('Menor que LIEAG')).toBeVisible(); + await expect(joint.getByText('LIEAG o más')).toBeVisible(); + // three HPV categories are not listed, and the page says so only when it has such reports + const hpvRows = await joint + .locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th') + .allInnerTexts(); + for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable']) + expect(hpvRows.join('|')).not.toContain(hidden); + // the cytology column reads one way at a time: the general table, or the clinical scenarios + const cytology = joint.locator('section[data-measure="CACU_EU7"]'); + await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked(); + await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0); + await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click(); + await expect(cytology.locator('.js-plotly-plot')).toBeVisible(); + await expect(cytology.getByRole('table')).toHaveCount(0); + await expect( + cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'), + ).toBeVisible(); + await expect(cytology.locator('.legend li')).toHaveCount(6); + await cytology.getByRole('radio', { name: 'Distribución general' }).click(); + await expect( + cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }), + ).toBeVisible(); + await expect( + joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'), + ).toHaveCount(0); + await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0); + // the confirmation card: one perspective at a time, each with its own PPV and its readings + const confirmation = tab.locator('.confirmation-card'); + await expect( + confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }), + ).toBeVisible(); + await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible(); + await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked(); + for (const [perspective, measure, title] of [ + ['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'], + ['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'], + ]) { + await confirmation.getByRole('radio', { name: perspective, exact: true }).click(); + await expect(confirmation.locator('app-ppv-card')).toHaveCount(1); + const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`); + await expect(ppv.getByRole('heading', { name: title })).toBeVisible(); + await expect(ppv.locator('.measure-score')).toContainText('IC 95 %'); + await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible(); + await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked(); + await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1); + await expect(ppv.locator('.ppv-rows')).toHaveCount(0); + for (const mode of [ + 'Citología previa', + 'VPH previo', + 'Nivel de histología', + 'Ronda de tamizaje', + ]) { + await ppv.getByRole('radio', { name: mode, exact: true }).click(); + await expect(ppv.getByRole('table', { name: mode })).toBeVisible(); + await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0); + await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/'); + // the score line and the methodological note stay in view in every reading + await expect(ppv.locator('.measure-score')).toContainText('IC 95 %'); + await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible(); + } + await ppv.getByRole('radio', { name: 'Total' }).click(); + await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1); + } + // the biopsy requests are one more reading of the biopsy perspective, with their own heading + const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]'); + await expect( + biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }), + ).toBeVisible(); + await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click(); + await expect( + biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }), + ).toBeVisible(); + await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount( + 0, + ); + await expect(biopsyPpv.locator('.measure-score')).toContainText( + 'solicitudes registradas (no pacientes)', + ); + await expect( + biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'), + ).toBeVisible(); + await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible(); + await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible(); + await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/'); + await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos'); + await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0); + await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click(); + await expect( + biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }), + ).toBeVisible(); + // the original confirmation measure is not shown on this tab any more + await expect(confirmation.locator('details')).toHaveCount(0); + await expect(tab.getByText('medida original')).toHaveCount(0); + await expect(tab.getByText('Denominador: ')).toHaveCount(0); + // the tabs are short and the full explanation is in the tab's content + await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click(); + const colposcopy = confirmation.locator('app-ppv-card'); + await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click(); + await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas'); + await expect(colposcopy.getByRole('radio')).toHaveCount(5); + const tops = await colposcopy + .locator('mat-button-toggle') + .evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size); + expect(tops).toBe(1); // one line on desktop + // the patients by HPV result: the whole as a donut, then one breakdown at a time + const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]'); + await expect(vph.locator('.measure-score')).toContainText('pacientes'); + await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible(); + await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked(); + await expect(vph.locator('.js-plotly-plot')).toHaveCount(1); + for (const mode of [ + 'Por grupo de edad', + 'Por estatus de seguimiento', + 'Por genotipo', + 'Por tamizaje inicial o subsecuente', + ]) { + await vph.getByRole('radio', { name: mode, exact: true }).click(); + await expect(vph.getByRole('table', { name: mode })).toBeVisible(); + await expect(vph.locator('.js-plotly-plot')).toHaveCount(0); + await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/'); + await expect(vph.locator('.measure-score')).toContainText('pacientes'); + } + await vph.getByRole('radio', { name: 'Total' }).click(); + await expect(vph.locator('.js-plotly-plot')).toHaveCount(1); + // the two HPV measures are told apart: reports against patients + await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText( + 'Pacientes evaluadas por resultado de VPH', + ); + await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText( + 'Cuenta reportes, no pacientes', + ); + expect(asked).toEqual([]); +}); + +test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({ + page, +}) => { + const problems = watch(page); + await page.goto('/indicadores/cacu'); + await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); + const rows = page.locator('table.worklist tbody tr:not(.stage-panel)'); + await expect(rows.first().locator('a')).toBeVisible(); + const total = async () => + Number( + /(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0, + ); + + // her age at the cut-off, and the stages: a compact line with a chevron that opens the panel + await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible(); + await expect(rows.first().locator('app-stages .node')).toHaveCount(5); + await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click(); + const panel = page.locator('tr.stage-panel'); + await expect(panel).toContainText('Toma de muestra'); + await expect(panel).toContainText('Desde anterior'); + await expect(panel.locator('.node')).toHaveCount(5); + await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click(); + await expect(panel).toHaveCount(0); + + // the age filters apply before the page is cut; the name search of Rebuild is still there + const all = await total(); + await page.getByLabel('Edad mínima').fill('200'); + await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible(); + await page.getByLabel('Edad mínima').fill('45'); + await expect(async () => expect(await total()).toBeLessThan(all)).toPass(); + await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible(); + await page.getByRole('button', { name: 'Limpiar edades' }).click(); + await expect(async () => expect(await total()).toBe(all)).toPass(); + + // the whole query, as the two files + const [pdf] = await Promise.all([ + page.waitForEvent('download'), + page.getByRole('button', { name: 'Exportar PDF' }).click(), + ]); + expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf'); + expect( + readFileSync((await pdf.path())!) + .subarray(0, 5) + .toString(), + ).toBe('%PDF-'); + const [xlsx] = await Promise.all([ + page.waitForEvent('download'), + page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(), + ]); + expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx'); + expect( + readFileSync((await xlsx.path())!) + .subarray(0, 2) + .toString(), + ).toBe('PK'); + + // her record: age, the detailed stages, the scales, and the file + await rows.first().locator('a').first().click(); + await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:'); + await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5); + await expect(page.getByText('Desde toma:').first()).toBeVisible(); + await expect(page.getByText('Riesgo inmediato')).toBeVisible(); + await expect(page.getByText('Riesgo a 5 años')).toBeVisible(); + const [ficha] = await Promise.all([ + page.waitForEvent('download'), + page.getByRole('button', { name: 'Exportar ficha PDF' }).click(), + ]); + expect( + readFileSync((await ficha.path())!) + .subarray(0, 5) + .toString(), + ).toBe('%PDF-'); + expect(problems).toEqual([]); +}); + /** Waits for a page's data: no loading indicator left. */ async function loaded(page: Page): Promise { await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, { diff --git a/src/app/export-document.ts b/src/app/export-document.ts new file mode 100644 index 0000000..d9b0fda --- /dev/null +++ b/src/app/export-document.ts @@ -0,0 +1,57 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { firstValueFrom } from 'rxjs'; + +export interface ExportStage { + state: string; + provenance?: string; + label?: string; + date?: string; + prev?: string; + start?: string; +} +export interface ExportRiskScale { + label: string; + value?: number; + low?: number; + high?: number; + outcome?: string; + model?: string; + horizon?: string; +} +export interface ExportDocument { + title: string; + parameters: string[][]; + columns: string[]; + rows: string[][]; + timeline?: ExportStage[]; + row_stages?: ExportStage[][]; + risk_scales?: ExportRiskScale[]; +} +export async function downloadDocument( + http: HttpClient, + format: 'pdf' | 'xlsx', + doc: ExportDocument, +) { + let blob: Blob; + try { + blob = await firstValueFrom( + http.post(`/api/cacu/exports/${format}`, doc, { responseType: 'blob' }), + ); + } catch (error) { + if (error instanceof HttpErrorResponse && error.error instanceof Blob) { + try { + const body = JSON.parse(await error.error.text()); + if (typeof body.detail === 'string') throw new Error(body.detail); + } catch (parsed) { + if (parsed instanceof Error && !(parsed instanceof SyntaxError)) throw parsed; + } + } + throw error; + } + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `cacu-${format === 'pdf' ? 'reporte.pdf' : 'seguimiento.xlsx'}`; + a.click(); + setTimeout(() => URL.revokeObjectURL(url), 60000); +} diff --git a/src/app/indicadores/cacu-results.spec.ts b/src/app/indicadores/cacu-results.spec.ts new file mode 100644 index 0000000..6811f31 --- /dev/null +++ b/src/app/indicadores/cacu-results.spec.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from 'vitest'; +import { + BIOPSY_REPORTS, + CYTOLOGY_REPORTS, + distribution, + durationMax, + durationRows, + HPV_REPORTS, + icdRows, + requests, + withoutHidden, +} from './cacu-results'; +import { PAGES } from './pages'; +import { PPV_NOTES, Reading, STRATA, name } from './measures'; + +const report = (population: number, counts: Record): Reading => ({ + populations: { 'initial-population': population }, + strata: { + category: Object.fromEntries( + Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]), + ), + }, +}); + +describe('distributions of reports', () => { + it('counts HPV reports and keeps inconsistent and zero categories', () => { + const d = distribution( + report(4, { negative: 2, positive_16: 1, inconsistent: 1 }), + HPV_REPORTS, + )!; + expect(d.total).toBe(4); + expect(d.rows.map((r) => r.count)).toEqual([2, 1, 0, 0, 0, 0, 1]); + expect(d.outside).toBe(0); + }); + + it('leaves what the table does not list outside it and says how much is without data', () => { + const d = distribution( + report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }), + BIOPSY_REPORTS, + )!; + expect(d.total).toBe(3); + expect(d.noData).toBe(1); + expect(d.outside).toBe(2); + }); + + it('does not invent a report: missing, or counts that do not add up, draw nothing; zero is zero', () => { + expect(distribution(undefined, HPV_REPORTS)).toBeUndefined(); + expect(distribution(report(2, { normal: 1 }), BIOPSY_REPORTS)).toBeUndefined(); + expect(distribution(report(0, {}), HPV_REPORTS)).toMatchObject({ + total: 0, + max: 0, + outside: 0, + }); + }); +}); + +describe('the categories a table leaves out', () => { + const hidden = ['positive_incomplete', 'inconsistent']; + it('lists the rest, keeps the total and the percentage denominator, and counts what it hides', () => { + const d = distribution( + report(10, { negative: 5, positive_16: 2, positive_incomplete: 2, inconsistent: 1 }), + HPV_REPORTS, + )!; + const v = withoutHidden(d, hidden); + expect(d.total).toBe(10); + expect(v.shown.map((r) => r.code)).not.toContain('positive_incomplete'); + expect(v.shown.map((r) => r.code)).not.toContain('inconsistent'); + expect(v.hiddenCount).toBe(3); + expect(v.max).toBe(5); + // nothing hidden: the rows are all of them and the count is zero (the page adds no note) + expect(withoutHidden(d).shown).toHaveLength(HPV_REPORTS.length); + expect(withoutHidden(d).hiddenCount).toBe(0); + }); + it('is the page choice for HPV; cytology and biopsy keep every category', () => { + const results = PAGES['cacu'].clinical.find((s) => s.kind === 'results')!; + if (results.kind !== 'results') throw new Error('no joint card'); + expect(results.hpv.hide).toEqual(hidden); + expect(results.cytology.hide).toBeUndefined(); + expect(results.biopsy.hide).toBeUndefined(); + expect(CYTOLOGY_REPORTS.map((r) => r[0])).toEqual([ + 'NILM', + 'ASC-US', + 'LSIL', + 'ASC-H', + 'HSIL', + 'CIS', + ]); + }); +}); + +describe('biopsy requests', () => { + it('reads every state of the request and keeps them apart from patients', () => { + const r = requests( + report(9, { high_grade: 3, below_high_grade: 2, pending: 2, no_grade: 1, ambiguous: 1 }), + )!; + expect(r).toMatchObject({ total: 9, high: 3, below: 2, pending: 2, noGrade: 1, ambiguous: 1 }); + expect(r.unclassified + r.inconsistent).toBe(0); + }); + + it('is none for a missing, failed or inconsistent report, and a zero total is a real zero', () => { + expect(requests(undefined)).toBeUndefined(); + expect(requests({ ...report(1, { pending: 1 }), error: true })).toBeUndefined(); + expect(requests(report(3, { pending: 1 }))).toBeUndefined(); + expect(requests(report(0, {}))?.total).toBe(0); + }); +}); + +describe('ICD-10 breakdown', () => { + it('lists each code with its median and quartiles, most frequent first', () => { + const r: Reading = { + populations: { 'initial-population': 3, 'measure-observation': 3 }, + strata: { + diagnosis_code: { + C53: { 'measure-observation': 2 }, + sin_codigo: { 'measure-observation': 1 }, + }, + }, + stratumScores: { + diagnosis_code: { + C53: { median: 30, low: 25, high: 40 }, + sin_codigo: { median: 12 }, + }, + }, + }; + expect(icdRows(r)).toEqual([ + { label: 'C53', count: 2, median: 30, low: 25, high: 40 }, + { label: 'Sin código disponible', count: 1, median: 12 }, + ]); + expect(icdRows(undefined)).toEqual([]); + }); +}); + +describe('route by steps', () => { + const at = (score?: number, n = 4, low?: number, high?: number): Reading => ({ + populations: { 'measure-observation': n }, + score, + low, + high, + strata: {}, + }); + + it('keeps every step, tells absent from zero and scales from zero to the largest quartile', () => { + const rows = durationRows([ + { label: 'a', r: at(0, 3, 0, 2) }, + { label: 'b', r: at(undefined) }, + { label: 'c', r: at(13, 4, 9, 41) }, + { label: 'd', r: undefined }, + ]); + expect(rows.map((r) => r.label)).toEqual(['a', 'b', 'c', 'd']); + expect(rows[0]).toMatchObject({ median: 0, observations: 3, low: 0, high: 2 }); + expect(rows[1].median).toBeUndefined(); + expect(rows[1].observations).toBeUndefined(); + expect(rows[3].median).toBeUndefined(); + expect(durationMax(rows)).toBe(41); + expect(durationMax(durationRows([{ label: 'x', r: undefined }]))).toBe(0); + }); +}); diff --git a/src/app/indicadores/cacu-results.ts b/src/app/indicadores/cacu-results.ts new file mode 100644 index 0000000..41bd1b6 --- /dev/null +++ b/src/app/indicadores/cacu-results.ts @@ -0,0 +1,167 @@ +import type { Reading } from './measures'; + +/** One category of a distribution: its code in the report, its words and its colour. */ +export type DistRow = readonly [code: string, label: string, color: string]; + +/** A distribution drawn as a table with a bar per category (CaCu's results of HPV and biopsy). */ +export interface Distribution { + rows: { code: string; label: string; color: string; count: number }[]; + /** units in the categories shown */ + total: number; + /** units of the period that are in none of them */ + outside: number; + max: number; + /** units the report counts as "no data" (no grade, no result) */ + noData: number; +} + +/** The categories of a report's `category` stratum, as counts of units. The strata must add up + * to the population: otherwise the report is not trusted and nothing is drawn. A category the + * report does not list is a zero, a missing report is not. */ +export function distribution( + reading: Reading | undefined, + categories: readonly DistRow[], +): Distribution | undefined { + const cells = reading?.strata['category']; + const population = reading?.populations['initial-population']; + if (!cells || population === undefined) return undefined; + const counts = Object.values(cells).map((cell) => cell['initial-population']); + if ( + counts.some((n) => n === undefined || !Number.isInteger(n) || n < 0) || + counts.reduce((a, b) => a + b, 0) !== population + ) + return undefined; + const rows = categories.map(([code, label, color]) => ({ + code, + label, + color, + count: cells[code]?.['initial-population'] ?? 0, + })); + const total = rows.reduce((sum, row) => sum + row.count, 0); + return { + rows, + total, + outside: population - total, + max: Math.max(0, ...rows.map((row) => row.count)), + noData: cells['no_data']?.['initial-population'] ?? 0, + }; +} + +/** Cytology results by Bethesda category (one sample per patient, the latest valid). */ +export const CYTOLOGY_REPORTS: readonly DistRow[] = [ + ['NILM', 'Normal', '#408651'], + ['ASC-US', 'ASC-US', '#2778B8'], + ['LSIL', 'LIEBG', '#B19525'], + ['ASC-H', 'ASC-H', '#7955B1'], + ['HSIL', 'LIEAG', '#CE4778'], + ['CIS', 'Carcinoma in situ', '#AA394D'], +]; + +/** The rows a table lists once some categories are left out of it: the total, the percentages and + * the units outside stay as the report gives them (nothing is recomputed); only the rows, the + * bars' scale and a count of what is not listed change. */ +export function withoutHidden(d: Distribution, hide: readonly string[] = []) { + const shown = d.rows.filter((r) => !hide.includes(r.code)); + return { + shown, + max: Math.max(0, ...shown.map((r) => r.count)), + hiddenCount: d.rows.filter((r) => hide.includes(r.code)).reduce((n, r) => n + r.count, 0), + }; +} + +/** HPV reports by genotype (one report per patient and sample date). */ +export const HPV_REPORTS: readonly DistRow[] = [ + ['negative', 'Negativo', '#42a77e'], + ['positive_16', 'Positivo 16 exclusivamente', '#df8640'], + ['positive_18', 'Positivo 18 exclusivamente', '#c29c42'], + ['positive_16_18', 'Positivo 16 y 18', '#c24269'], + ['positive_other', 'Positivo sin detección de 16/18', '#a8c243'], + ['positive_incomplete', 'Positivo con genotipificación incompleta', '#9c42c2'], + ['inconsistent', 'No clasificable o inconsistente', '#687786'], +]; + +/** Biopsy reports by the grade they state. */ +export const BIOPSY_REPORTS: readonly DistRow[] = [ + ['normal', 'Normal', '#408651'], + ['LSIL', 'LIEBG (CIN 1)', '#B19525'], + ['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'], + ['CIS', 'Carcinoma in situ', '#AA394D'], + ['carcinoma', 'Carcinoma invasor', '#8D4C79'], +]; + +/** The ICD-10 codes of the diagnosis notes, each with its median and quartiles of days from the + * sample to the diagnosis (an exploratory grouping by the dates that link them). */ +export function icdRows(reading: Reading | undefined) { + const scores = reading?.stratumScores?.['diagnosis_code'] ?? {}; + return Object.entries(scores) + .map(([label, score]) => ({ + label: label + .replace('sin_codigo', 'Sin código disponible') + .replace('ambiguo', 'Diagnóstico ambiguo'), + count: reading?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0, + ...score, + })) + .sort((a, b) => b.count - a.count || a.label.localeCompare(b.label)); +} + +/** The biopsy requests on record by their state at the cut-off; they are requests, not patients. */ +export interface Requests { + total: number; + high: number; + below: number; + pending: number; + noGrade: number; + unclassified: number; + inconsistent: number; + ambiguous: number; +} + +/** None when the report is missing, errored or does not add up (the page then says so). */ +export function requests(reading: Reading | undefined): Requests | undefined { + const total = reading?.populations['initial-population']; + const cells = reading?.strata['category']; + if (!reading || reading.error || total === undefined || !cells) return undefined; + const counts = Object.values(cells).map((cell) => cell['initial-population']); + if ( + !Number.isInteger(total) || + total < 0 || + counts.some((n) => !Number.isInteger(n) || n < 0) || + counts.reduce((sum, n) => sum + n, 0) !== total + ) + return undefined; + const of = (key: string) => cells[key]?.['initial-population'] ?? 0; + return { + total, + high: of('high_grade'), + below: of('below_high_grade'), + pending: of('pending'), + noGrade: of('no_grade'), + unclassified: of('unclassified'), + inconsistent: of('inconsistent'), + ambiguous: of('ambiguous'), + }; +} + +/** One row of a duration table: the median days, how many measurements and the quartiles. A + * step with no median keeps its row and says nothing (absent is not zero). */ +export interface DurationRow { + label: string; + median?: number; + observations?: number; + low?: number; + high?: number; +} + +export function durationRows(steps: { label: string; r: Reading | undefined }[]): DurationRow[] { + return steps.map(({ label, r }) => ({ + label, + median: r?.score, + observations: r?.score === undefined ? undefined : r.populations['measure-observation'], + low: r?.score === undefined ? undefined : r.low, + high: r?.score === undefined ? undefined : r.high, + })); +} + +/** The scale of a table of durations, from zero: the largest median or third quartile shown. */ +export const durationMax = (rows: DurationRow[]): number => + Math.max(0, ...rows.map((r) => Math.max(r.median ?? 0, r.high ?? 0))); diff --git a/src/app/indicadores/confirmation.spec.ts b/src/app/indicadores/confirmation.spec.ts new file mode 100644 index 0000000..8ef360d --- /dev/null +++ b/src/app/indicadores/confirmation.spec.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from 'vitest'; +import { requestsAlternate } from './confirmation'; +import { Reading } from './measures'; + +const report = (population: number, counts: Record): Reading => ({ + populations: { 'initial-population': population }, + strata: { + category: Object.fromEntries( + Object.entries(counts).map(([k, n]) => [k, { 'initial-population': n }]), + ), + }, +}); + +describe('biopsy requests as a reading of the biopsy card', () => { + it('keeps the request denominator, bars and secondary counts of the old card', () => { + const a = requestsAlternate(report(13, { high_grade: 9, below_high_grade: 4 }), true); + expect(a.score).toBe('69.2 %'); + expect(a.detail).toContain('9 de 13 solicitudes registradas (no pacientes)'); + expect(a.rows.map((r) => [r.label, r.numerator, r.denominator])).toEqual([ + ['LIEAG o más', 9, 13], + ['Menor que LIEAG', 4, 13], + ]); + expect(a.lines[0]).toContain('Pendientes: 0 · Sin grado: 0 · No clasificables: 0'); + expect(a.note).toContain('no se pide un corte histórico (as-of)'); + }); + + it('shows pending and ungraded requests in the denominator, not as a result', () => { + const a = requestsAlternate( + report(10, { high_grade: 2, below_high_grade: 1, pending: 4, no_grade: 2, ambiguous: 1 }), + true, + ); + expect(a.rows[0].denominator).toBe(10); + expect(a.lines[0]).toContain('Pendientes: 4 · Sin grado: 2'); + expect(a.lines[0]).toContain('ambiguos: 1'); + }); + + it('tells no records (a zero) from a missing, failed or inconsistent report', () => { + expect(requestsAlternate(report(0, {}), true).message).toContain('denominador 0'); + expect(requestsAlternate(report(0, {}), true).score).toBe('0 solicitudes'); + expect(requestsAlternate(undefined, true).message).toContain('No disponible para este periodo'); + expect(requestsAlternate(undefined, false).message).toContain('no publicada'); + const failed = requestsAlternate({ ...report(1, { pending: 1 }), error: true }, true); + expect(failed.alert).toBe(true); + expect(requestsAlternate(report(5, { pending: 1 }), true).alert).toBe(true); + }); +}); diff --git a/src/app/indicadores/confirmation.ts b/src/app/indicadores/confirmation.ts new file mode 100644 index 0000000..87c1f80 --- /dev/null +++ b/src/app/indicadores/confirmation.ts @@ -0,0 +1,73 @@ +import { requests } from './cacu-results'; +import { Reading } from './measures'; +import { PpvAlternate } from './ppv'; + +/** The biopsy requests as one more reading of the biopsy PPV card. They are requests, not + * patients, and the denominator is every request on record (pending and ungraded ones too); the + * histological threshold is high grade (LIEAG or more), not the PPV's LIEBG or more. */ +export function requestsAlternate(reading: Reading | undefined, published: boolean): PpvAlternate { + const base = { + label: 'Solicitudes de biopsia', + title: 'Confirmación por solicitudes de biopsia registradas', + note: + 'La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones. ' + + 'Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud; no se pide un corte ' + + 'histórico (as-of) porque la medida no lo admite.', + caption: + 'Solicitudes, no pacientes: cada barra cuenta las solicitudes con ese resultado sobre todas las solicitudes ' + + 'registradas, incluidas las pendientes y las que no tienen grado.', + rows: [], + lines: [], + }; + const without = (message: string, score = 'Sin dato', alert = false): PpvAlternate => ({ + ...base, + score, + detail: '', + message, + alert, + }); + if (!published) return without('No disponible: medida no publicada por el servidor.'); + if (reading?.error) + return without('No se pudo consultar las solicitudes de biopsia.', 'Sin dato', true); + if (!reading) return without('No disponible para este periodo.'); + const r = requests(reading); + if (!r) + return without( + 'Los datos de solicitudes recibidos están incompletos o son inconsistentes.', + 'Sin dato', + true, + ); + if (!r.total) + return without( + 'Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).', + '0 solicitudes', + ); + const share = (n: number) => (100 * n) / r.total; + return { + ...base, + score: `${share(r.high).toFixed(1)} %`, + detail: `${r.high} de ${r.total} solicitudes registradas (no pacientes) con histología LIEAG o más.`, + rows: [ + { + code: 'high_grade', + label: 'LIEAG o más', + color: '#CE4778', + numerator: r.high, + denominator: r.total, + percent: share(r.high), + }, + { + code: 'below_high_grade', + label: 'Menor que LIEAG', + color: '#8FA7BB', + numerator: r.below, + denominator: r.total, + percent: share(r.below), + }, + ], + lines: [ + `Pendientes: ${r.pending} · Sin grado: ${r.noGrade} · No clasificables: ${r.unclassified} · ` + + `Fechas inconsistentes: ${r.inconsistent} · Registros fusionados ambiguos: ${r.ambiguous}.`, + ], + }; +} diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts index bd2fe5e..f179334 100644 --- a/src/app/indicadores/figures.ts +++ b/src/app/indicadores/figures.ts @@ -12,38 +12,6 @@ function rgba(hex: string, alpha: number): string { return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`; } -/** The screening route: each step's median days from the sample, with Q1–Q3. */ -export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure { - const shown = steps.filter((s) => s.r?.score !== undefined); - return { - data: [ - { - type: 'bar', - orientation: 'h', - y: shown.map( - (s) => `${s.label}
n = ${count(s.r!.populations['measure-observation'] ?? 0)}`, - ), - x: shown.map((s) => s.r!.score!), - marker: { color: OLIVE }, - error_x: { - type: 'data', - symmetric: false, - thickness: 1.5, - width: 6, - array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!), - arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)), - }, - hovertemplate: '%{y}
mediana %{x} días', - } as Partial, - ], - layout: { - showlegend: false, - xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false }, - yaxis: { autorange: 'reversed', type: 'category', automargin: true }, - }, - }; -} - /** A category's count in the report (the composition's `category` stratum). */ function counted(r: Reading, code: string): number { return r.strata['category']?.[code]?.['initial-population'] ?? 0; @@ -122,7 +90,9 @@ export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figur }; } -/** Each clinical scenario's results as shares of its patients, one stacked bar each. */ +/** A result's share inside each clinical scenario (the report's `-category` cells): + * each bar is 100 % of the patients of that scenario with a result in the catalogue, and its + * label says how many they are. Compact: a one-line legend above and thin bars. */ export function scenarioBars( r: Reading, catalog: Catalog, @@ -135,25 +105,36 @@ export function scenarioBars( ); const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0; const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0)); - const y = scenarios.map(label); + const y = scenarios.map((s, i) => `${label(s)}
n = ${count(totals[i])}`); + const share = (s: string, i: number, c: string) => (totals[i] ? (100 * n(s, c)) / totals[i] : 0); return { data: catalog.categories.map((c) => ({ type: 'bar', orientation: 'h', name: c.label, y, - x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)), + x: scenarios.map((s, i) => share(s, i, c.code)), customdata: scenarios.map((s) => n(s, c.code)), + text: scenarios.map((s, i) => + share(s, i, c.code) >= 12 ? `${percent(share(s, i, c.code))} %` : '', + ), + textposition: 'inside', + insidetextanchor: 'middle', + textangle: 0, + textfont: { color: '#ffffff', size: 11 }, marker: { color: c.color }, hovertemplate: `${c.label}
%{y}: %{customdata} (%{x:.1f} %)`, })) as Partial[], layout: { barmode: 'stack', + bargap: 0.35, + showlegend: false, // the page draws the legend, which wraps on a narrow screen + margin: { t: 8, r: 8, b: 40, l: 8 }, xaxis: { - title: { text: '% de pacientes del escenario con resultado' }, + title: { text: '% de las pacientes del escenario con resultado', font: { size: 11 } }, ticksuffix: ' %', range: [0, 100.5], - dtick: 20, + dtick: 25, }, yaxis: { type: 'category', diff --git a/src/app/indicadores/follow-up.spec.ts b/src/app/indicadores/follow-up.spec.ts index 8eceef2..e9dd796 100644 --- a/src/app/indicadores/follow-up.spec.ts +++ b/src/app/indicadores/follow-up.spec.ts @@ -1,8 +1,56 @@ -import type { RiskAssessment } from 'fhir/r4'; -import { ageGroup, currentRisk, windowStart } from './follow-up'; +import '@angular/compiler'; +import { describe, expect, it } from 'vitest'; +import type { Patient, RiskAssessment } from 'fhir/r4'; +import { + ageGroup, + currentRisk, + exactAge, + patientLabel, + patientName, + rows, + windowStart, +} from './follow-up'; import { periods } from './measures'; describe('follow-up list', () => { + it('uses synthetic FHIR names consistently and keeps the patient id as fallback', () => { + const patient: Patient = { + resourceType: 'Patient', + id: 'abcdef123456', + name: [{ text: ' Ana Ejemplo ' }], + }; + const page = { + resourceType: 'Bundle' as const, + type: 'searchset' as const, + entry: [{ resource: patient, search: { mode: 'match' as const } }], + }; + expect(rows(page, '2026-01-01', '2026-11-27', 5)[0].name).toBe('Ana Ejemplo'); + expect(patientLabel(patient)).toBe('Ana Ejemplo'); + expect( + patientName({ ...patient, name: [{ given: ['Ana', 'María'], family: 'Ejemplo' }] }), + ).toBe('Ana María Ejemplo'); + expect(patientLabel({ ...patient, name: [{ text: ' ' }] })).toBe('abcdef1234'); + }); + it('calculates completed years only from valid full dates', () => { + expect(exactAge('1980-11-23', '2026-11-22')).toBe(45); + expect(exactAge('1980-11-23', '2026-11-23')).toBe(46); + expect(exactAge('2000-02-29', '2025-02-28')).toBe(24); + expect(exactAge('2000-02', '2026-01-01')).toBeUndefined(); + expect(exactAge('2001-02-29', '2026-01-01')).toBeUndefined(); + expect(exactAge('2027-01-01', '2026-01-01')).toBeUndefined(); + }); + it('keeps a missing prediction separate from zero', () => { + const risk = (p?: number): RiskAssessment => ({ + resourceType: 'RiskAssessment', + status: 'final', + subject: {}, + occurrenceDateTime: '2026-01-01', + method: { coding: [{ code: 'cacu.cin2_pim' }] }, + prediction: [{ probabilityDecimal: p, whenRange: { high: { value: 5 } } }], + }); + expect(currentRisk([risk()], 'cin2', 5)).toBeUndefined(); + expect(currentRisk([risk(0)], 'cin2', 5)).toBe(0); + }); it('starts the window the day after the same day months before (core.follow_up)', () => { expect(windowStart('2026-11-22', 3)).toBe('2026-08-23'); expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts index 435be37..56e72b7 100644 --- a/src/app/indicadores/follow-up.ts +++ b/src/app/indicadores/follow-up.ts @@ -1,5 +1,6 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import { code, ext, resources } from '../fhir'; +import { routeFacts, StageFacts } from '../paciente/stages'; /** One row of the follow-up list: what the list shows of a patient at the cut-off. */ export interface Row { @@ -8,7 +9,9 @@ export interface Row { curp?: string; status: string; ageGroup: string; - cytology?: { date: string; result?: string; adequacy?: string }; + age?: number; + stageFacts: StageFacts; + cytology?: { date: string; reportDate?: string; result?: string; adequacy?: string }; hpv?: { date: string; positive: boolean; types1618?: boolean }; daysToDiagnosis?: number; biopsy?: { date: string; histology?: string }; @@ -17,6 +20,42 @@ export interface Row { export const CURP = 'https://isssteleon.org/fhir/sid/curp'; +/** Prefer the supplied FHIR display text, then a structured name, then the next name. */ +export function patientName(patient: Patient | undefined): string | undefined { + for (const name of patient?.name ?? []) { + const text = name.text?.trim(); + if (text) return text; + const parts = [...(name.given ?? []), name.family ?? ''] + .map((part) => part.trim()) + .filter(Boolean); + if (parts.length) return parts.join(' '); + } + return undefined; +} + +export function patientLabel(patient: Patient | undefined): string { + return patientName(patient) ?? patient?.id?.slice(0, 10) ?? 'No disponible'; +} + +/** Completed years on a full, valid calendar date; partial dates are unknown. */ +export function exactAge( + birth: string | undefined, + cutoff: string | undefined, +): number | undefined { + const parse = (text?: string): [number, number, number] | undefined => { + if (!text || !/^\d{4}-\d{2}-\d{2}$/.test(text)) return undefined; + const [y, m, d] = text.split('-').map(Number); + if (y < 1 || m < 1 || m > 12 || d < 1) return undefined; + const leap = y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0); + if (d > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]) return undefined; + return [y, m, d]; + }; + const b = parse(birth), + c = parse(cutoff); + if (!b || !c || birth! > cutoff!) return undefined; + return c[0] - b[0] - (c[1] < b[1] || (c[1] === b[1] && c[2] < b[2]) ? 1 : 0); +} + const AGE_GROUPS: [number, number][] = [ [25, 34], [35, 44], @@ -49,7 +88,7 @@ export function currentRisk( .filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`)) .flatMap((r) => (r.prediction ?? []) - .filter((p) => p.whenRange?.high?.value === horizon) + .filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined) .map((p) => ({ r, p })), ); if (!mine.length) return undefined; @@ -58,9 +97,7 @@ export function currentRisk( .sort() .at(-1); return Math.max( - ...mine - .filter((x) => x.r.occurrenceDateTime === latest) - .map((x) => x.p.probabilityDecimal ?? 0), + ...mine.filter((x) => x.r.occurrenceDateTime === latest).map((x) => x.p.probabilityDecimal!), ); } @@ -99,12 +136,15 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`); return { patient, - name: patient.name?.[0]?.text, + name: patientName(patient), curp: patient.identifier?.find((i) => i.system === CURP)?.value, status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', ageGroup: ageGroup(patient.birthDate, cutoff), + age: exactAge(patient.birthDate, cutoff), + stageFacts: routeFacts(last), cytology: last && { date: last.effectiveDateTime!, + reportDate: ext(last, 'report-date')?.valueDate, result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept), adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept), }, @@ -187,7 +227,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] { .at(-1); return { patient, - name: patient.name?.[0]?.text, + name: patientName(patient), curp: patient.identifier?.find((i) => i.system === CURP)?.value, status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '', diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 047ff6e..b8e2b6d 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -44,12 +44,17 @@ export function periodTypes(measure: Measure): PeriodType[] { /** What one report says: its counts, its score and interval, and its strata. */ export interface Reading { + /** The server refused or failed the report (a measure that was asked for, not an empty one). */ + error?: boolean; populations: Record; score?: number; low?: number; high?: number; unit?: string; strata: Record>>; + /** A stratum's own score by stratifier and value: a median with its quartiles, or a + * proportion with its interval, whichever the report publishes. */ + stratumScores?: Record>; } function counts(group: { @@ -65,6 +70,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined if (!group) return undefined; const score = group.measureScore; const strata: Reading['strata'] = {}; + const stratumScores: NonNullable = {}; for (const s of group.stratifier ?? []) { // A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`. const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-'); @@ -76,6 +82,18 @@ export function reading(report: MeasureReport | undefined): Reading | undefined counts(x), ]), ); + stratumScores[name] = Object.fromEntries( + (s.stratum ?? []) + .filter((x) => x.measureScore?.value !== undefined) + .map((x) => [ + x.value?.text ?? '', + { + median: x.measureScore!.value!, + low: (ext(x.measureScore, 'q1') ?? ext(x.measureScore, 'ic-bajo'))?.valueDecimal, + high: (ext(x.measureScore, 'q3') ?? ext(x.measureScore, 'ic-alto'))?.valueDecimal, + }, + ]), + ); } return { populations: counts(group), @@ -84,6 +102,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, unit: score?.unit, strata, + stratumScores, }; } @@ -122,6 +141,17 @@ export const LABELS: Record = { good: 'Bueno', bad: 'Malo', not_analyzed: 'Sin analizar', + 'ASCUS+': 'Citología ASC-US o mayor', + 'LSIL+': 'Citología LIEBG o mayor', + 'HSIL+': 'Citología LIEAG o mayor', + 'LIEBG+': 'Histología LIEBG o mayor', + 'LIEAG+': 'Histología LIEAG o mayor', + initial: 'Tamizaje inicial', + subsequent: 'Tamizaje subsecuente', + positive: 'Positivo', + negative: 'Negativo', + hpv_16: 'Positivo para VPH 16', + hpv_18: 'Positivo para VPH 18', ...Object.fromEntries( ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ), @@ -134,7 +164,43 @@ export const STRATA: Record = { follow_up_status: 'Estatus de seguimiento', result: 'Citología de alto grado', birads: 'BI-RADS de la mastografía', + referral_cytology: 'Citología previa asociada por fechas', + referral_hpv: 'VPH de la citología previa asociada por fechas', + histology_level: 'Nivel de histología confirmado', + screening_round: 'Tamizaje inicial o subsecuente', + result_initial: 'Resultado en tamizaje inicial', + result_subsequent: 'Resultado en tamizaje subsecuente', + hpv_16: 'VPH 16', + hpv_18: 'VPH 18', + hpv_initial: 'VPH en tamizaje inicial', + hpv_subsequent: 'VPH en tamizaje subsecuente', }; +/** What the referral PPVs are: the records show procedures, not issued referrals, and the + * previous cytology is linked by dates. */ +export const PPV_NOTES: Record = { + CACU_VPP_COLPOSCOPIA: { + title: 'VPP tras colposcopía registrada', + note: + 'De las pacientes con colposcopía registrada en el periodo (puede inferirse de notas clínicas), ' + + 'las que tienen histología LIEBG o mayor. Se muestra la citología previa más reciente en los 365 ' + + 'días anteriores: es una asociación por fechas, no un vínculo clínico confirmado ni una referencia emitida.', + }, + CACU_VPP_BIOPSIA: { + title: 'VPP tras biopsia registrada', + note: + 'De las pacientes con biopsia reportada en el periodo, las que tienen histología LIEBG o mayor. ' + + 'La citología previa es una asociación por fechas, no un vínculo clínico confirmado ni una referencia ' + + 'emitida. Su denominador difiere del de las solicitudes de biopsia registradas.', + }, + CACU_VPH: { + title: 'Pacientes evaluadas por resultado de VPH (última muestra con resultado)', + note: + 'Una paciente por periodo, por su última muestra con resultado de VPH, aunque la citología no tenga ' + + 'resultado. Es distinto de los reportes de VPH por genotipo, que cuentan reportes, no pacientes.', + }, +}; +export const measureTitle = (m: { name?: string; title?: string }) => + PPV_NOTES[m.name ?? '']?.title ?? m.title ?? m.name ?? ''; export const name = (value: string) => LABELS[value] ?? value; export function formatScore(measure: Measure, r: Reading | undefined): string { @@ -215,6 +281,17 @@ export function strataBars(measure: Measure, r: Reading, stratifier: string): Fi y: cells.map(([v]) => name(v)), x: values, marker: { color: PALETTE[0] }, + ...(proportion + ? { + text: cells.map(([, c]) => + c['denominator'] + ? `${c['numerator'] ?? 0} de ${c['denominator']}` + : 'sin pacientes', + ), + textposition: 'auto' as const, + hovertemplate: '%{y}
%{x:.1f} % (%{text})', + } + : {}), }, ], layout: { diff --git a/src/app/indicadores/pages.ts b/src/app/indicadores/pages.ts index b33bbf2..4a77e5f 100644 --- a/src/app/indicadores/pages.ts +++ b/src/app/indicadores/pages.ts @@ -17,8 +17,56 @@ export interface Kpi { value?: string; note?: string; } +/** A measure's categories as a table with a bar each; say what is counted. */ +export interface DistSpec { + title: string; + measure: string; + /** what the units are, in the plural */ + unit: string; + /** the categories, and which of them to head with a group line */ + catalog: readonly (readonly [string, string, string])[]; + groups?: { before: string; label: string; codes: string[] }[]; + notes: string[]; + /** categories left out of the table (their units stay in the total and the percentages) */ + hide?: string[]; +} export type Section = - | { kind: 'route'; title: string; steps: { label: string; measure: string }[] } + | { + kind: 'route'; + title: string; + /** `measure`: days from the sample to the step; `stepMeasure`: days from the previous step */ + steps: { label: string; measure: string; step?: string; stepMeasure?: string }[]; + /** the route in three readings: cumulative, step by step, and by the ICD-10 of the diagnosis */ + modes?: { icd: string }; + } + /** CaCu's joint card: the cytology and HPV distributions side by side, the biopsy's below, and + * the scenario figure as a complement. */ + | { + kind: 'results'; + title: string; + cytology: DistSpec; + hpv: DistSpec; + biopsy: DistSpec; + complement: FigureSpec[]; + } + /** A positive predictive value read one way at a time (the whole, or a stratifier). */ + | { + kind: 'ppv'; + measure: string; + modes: PpvMode[]; + /** the heading figures when the measure is not a proportion */ + summary?: (reading: Reading | undefined) => { score: string; detail: string }; + } + /** The generic card of a measure: its score with numerator, denominator and interval, and its strata. */ + | { kind: 'measure-card'; measure: string } + /** The histopathological confirmation: one card, two perspectives (a colposcopy and a biopsy + * PPV), the biopsy requests as one more reading of the biopsy one, and the original measure */ + | { + kind: 'confirmation'; + title: string; + colposcopy: { measure: string; modes: PpvMode[] }; + biopsy: { measure: string; modes: PpvMode[]; requests: string }; + } | { kind: 'figures'; title?: string; figures: FigureSpec[] } | { kind: 'boxes'; @@ -77,39 +125,21 @@ export interface Catalog { faded?: string[]; } +import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results'; +import { Reading } from './measures'; +import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, PpvMode } from './ppv'; +import { VPH_MODES, vphSummary } from './vph'; + const OLIVE = '#A8C243'; const ROSE = '#C24269'; -/** Bethesda results as the old app grouped and coloured them. */ -const CYTOLOGY: Catalog = { - groups: [ - { id: 'normal', label: 'Sin anomalía', color: OLIVE }, - { id: 'abnormal', label: 'Anormal', color: ROSE }, - ], - categories: [ - { code: 'NILM', label: 'Normal', color: '#A8C243', group: 'normal' }, - { code: 'ASC-US', label: 'ASC-US', color: '#92324F', group: 'abnormal' }, - { code: 'LSIL', label: 'LIEBG', color: '#AA3A5C', group: 'abnormal' }, - { code: 'ASC-H', label: 'ASC-H', color: '#C24269', group: 'abnormal' }, - { code: 'HSIL', label: 'LIEAG', color: '#C54C71', group: 'abnormal' }, - { code: 'CIS', label: 'Carcinoma in situ', color: '#C9577A', group: 'abnormal' }, - ], -}; +/** HPV categories the page leaves out (their reports stay in the total and the percentages). */ +const HPV_HIDDEN = ['positive_incomplete', 'inconsistent']; -/** Biopsy grades: below high grade, and high grade or worse (what confirmation counts). */ -const BIOPSY: Catalog = { - groups: [ - { id: 'low', label: 'Menor que LIEAG', color: OLIVE }, - { id: 'high', label: 'LIEAG o más', color: ROSE }, - ], - categories: [ - { code: 'normal', label: 'Normal', color: '#7E9232', group: 'low' }, - { code: 'LSIL', label: 'LIEBG (CIN 1)', color: '#B2C958', group: 'low' }, - { code: 'HSIL', label: 'LIEAG (CIN 2 y 3)', color: '#92324F', group: 'high' }, - { code: 'CIS', label: 'Carcinoma in situ', color: '#C24269', group: 'high' }, - { code: 'carcinoma', label: 'Carcinoma invasor', color: '#C9577A', group: 'high' }, - ], - faded: ['normal', 'LSIL'], +/** The cytology results by scenario, in the page's cytology colours. */ +const CYTOLOGY_SCENARIO: Catalog = { + groups: [], + categories: CYTOLOGY_REPORTS.map(([code, label, color]) => ({ code, label, color, group: '' })), }; const CACU_DAYS = { @@ -372,58 +402,98 @@ export const PAGES: Record = { ...CACU_DAYS, }, ], - clinical: [ + opportunity: [ { kind: 'route', title: 'Tiempos de la ruta del tamizaje', + modes: { icd: 'CACU_TIEMPO_DIAGNOSTICO_CIE10' }, steps: [ - { label: 'Resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' }, - { label: 'Resultado de colposcopía', measure: 'CACU_DIAS_TOMA_COLPOSCOPIA' }, - { label: 'Resultado de biopsia', measure: 'CACU_DIAS_TOMA_BIOPSIA' }, - { label: 'Diagnóstico', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO' }, - ], - }, - { - kind: 'figures', - title: 'Distribución de resultados citológicos', - figures: [ { - kind: 'donut', - title: 'Distribución de resultados, {p}', - measure: 'CACU_EU7', - catalog: CYTOLOGY, - center: 'pacientes', + label: 'Resultado de citología', + measure: 'CACU_EU_TIEMPO_REPORTE', + step: 'Toma a resultado de citología', + stepMeasure: 'CACU_EU_TIEMPO_REPORTE', }, + { + label: 'Resultado de colposcopía', + measure: 'CACU_DIAS_TOMA_COLPOSCOPIA', + step: 'Del resultado de citología a la colposcopía', + stepMeasure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA', + }, + { + label: 'Resultado de biopsia', + measure: 'CACU_DIAS_TOMA_BIOPSIA', + step: 'De la colposcopía al resultado de biopsia', + stepMeasure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA', + }, + { + label: 'Diagnóstico', + measure: 'CACU_DIAS_TOMA_DIAGNOSTICO', + step: 'Del resultado de biopsia al diagnóstico', + stepMeasure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO', + }, + ], + }, + ], + clinical: [ + { + kind: 'results', + title: 'Resultados de citología, VPH y biopsia', + cytology: { + title: 'Distribución de resultados citológicos', + measure: 'CACU_EU7', + unit: 'pacientes', + catalog: CYTOLOGY_REPORTS, + notes: [ + 'Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.', + ], + }, + hpv: { + title: 'Resultados de VPH por genotipo', + measure: 'CACU_VPH_GENOTIPO', + unit: 'reportes', + catalog: HPV_REPORTS, + hide: HPV_HIDDEN, + notes: [ + 'Un reporte de VPH por paciente y fecha de toma; el periodo es el de la toma. Cuenta reportes, ' + + 'no pacientes: es una medida distinta de las pacientes evaluadas por resultado de VPH.', + 'Los valores nulos no se cuentan como negativos.', + ], + }, + biopsy: { + title: 'Resultados de biopsia cervical', + measure: 'CACU_BIOPSIA_RESULTADOS', + unit: 'reportes', + catalog: BIOPSY_REPORTS, + groups: [ + { before: 'normal', label: 'Menor que LIEAG', codes: ['normal', 'LSIL'] }, + { before: 'HSIL', label: 'LIEAG o más', codes: ['HSIL', 'CIS', 'carcinoma'] }, + ], + notes: [ + 'Reportes de biopsia con histología clasificable; el periodo es el de la fecha del reporte. ' + + 'Las órdenes sin reporte no están incluidas.', + ], + }, + complement: [ { kind: 'scenario-bars', - title: 'TOTAL por escenario clínico, {p}', + title: 'Resultados citológicos por escenario clínico, {p}', measure: 'CACU_EU7', - catalog: CYTOLOGY, + catalog: CYTOLOGY_SCENARIO, stratum: 'follow_up_status', }, ], }, + { kind: 'ppv', measure: 'CACU_VPH', modes: VPH_MODES, summary: vphSummary }, { - kind: 'figures', + kind: 'confirmation', title: 'Tasa de confirmación histopatológica', - figures: [ - { - kind: 'rates', - title: 'Por resultado de la citología, {p}', - measure: 'CACU_CONFIRMACION_CITOLOGIA', - stratum: 'result', - rows: CYTOLOGY.categories.filter((c) => ['ASC-H', 'HSIL', 'CIS'].includes(c.code)), - positive: ['HSIL', 'CIS', 'carcinoma'], - axis: 'Verdaderos positivos (valor predictivo positivo)', - }, - { - kind: 'donut', - title: 'Resultado de la biopsia, {p}', - measure: 'CACU_CONFIRMACION_CITOLOGIA', - catalog: BIOPSY, - center: 'con biopsia', - }, - ], + colposcopy: { measure: 'CACU_VPP_COLPOSCOPIA', modes: PPV_COLPOSCOPY_MODES }, + biopsy: { + measure: 'CACU_VPP_BIOPSIA', + modes: PPV_BIOPSY_MODES, + requests: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', + }, }, ], }, diff --git a/src/app/indicadores/ppv-card.html b/src/app/indicadores/ppv-card.html new file mode 100644 index 0000000..59decde --- /dev/null +++ b/src/app/indicadores/ppv-card.html @@ -0,0 +1,160 @@ + + @if (embedded()) { +

{{ text }}

+ } @else { +

{{ text }}

+ } +
+ + + @let withInterval = hasInterval(rows); +
+
+ Grupo + + 0 %50 %100 % + + n/N + {{ percent ?? '%' }} + @if (withInterval) { + IC 95 % + } +
+ @for (row of rows; track row.code) { +
+ {{ row.label }} + + {{ row.numerator }}/{{ row.denominator }} + + {{ row.percent === undefined ? '—' : fixed(row.percent) + ' %' }} + + @if (withInterval) { + + {{ + row.low === undefined || row.high === undefined + ? '—' + : fixed(row.low) + '–' + fixed(row.high) + ' %' + }} + + } +
+ } +
+ @if (!withInterval) { +

El servidor no publica el intervalo por grupo.

+ } +
+ + + + @for (m of modes(); track m.id) { + {{ m.label }} + } + @if (alternate(); as a) { + {{ a.label }} + } + + + + + @if (loading()) { + + + } @else if (alternate(); as a) { + @if (selected() === 'alternate') { + +

{{ a.score }}{{ a.detail ? ' · ' + a.detail : '' }}

+ @if (a.note) { +

{{ a.note }}

+ } + + @if (a.message) { +

{{ a.message }}

+ } @else { +

{{ a.caption }}

+ + @for (line of a.lines; track line) { +

{{ line }}

+ } + } + } @else { + + } + } @else { + + } +
+ + + + @if (!published()) { +

Medida no publicada por el servidor.

+ @if (alternate()) { + + } + } @else if (reading()?.error) { + + @if (alternate()) { + + } + } @else { +

{{ score() }} · {{ detail() }}

+ @if (note()) { +

{{ note() }}

+ } + @if (empty() && !alternate()) { +

Sin pacientes en el periodo.

+ } @else { + + @if (empty()) { +

Sin pacientes en el periodo.

+ } @else { +

{{ mode().caption }}

+ @if (!mode().stratum && !mode().rows) { + @if (donut(); as figure) { + + } @else { +

El reporte no trae numerador y denominador consistentes.

+ } + } @else if (rows().length) { + + } @else { +

Sin pacientes en esta lectura en el periodo.

+ } + } + } + } +
+ +@if (embedded()) { +
+ +
+} @else { + + + + + +} diff --git a/src/app/indicadores/ppv-card.scss b/src/app/indicadores/ppv-card.scss new file mode 100644 index 0000000..079868d --- /dev/null +++ b/src/app/indicadores/ppv-card.scss @@ -0,0 +1,91 @@ +:host { + display: block; +} +.figure-card { + margin-top: 24px; +} +h2.figure-card-title { + font-size: 18px; + font-weight: 500; + margin: 0 0 12px; +} +.measure-score { + font-weight: 500; + margin: var(--space-2) 0; +} +.state { + color: var(--color-text-secondary); + font-size: 14px; +} +.ppv-modes { + flex-wrap: wrap; + margin: var(--space-3) 0 var(--space-2); + max-width: 100%; +} +.ppv-caption { + font-size: 13px; + margin: var(--space-2) 0; +} +.ppv-rows { + font-size: 13px; + margin-top: var(--space-2); +} +.ppv-row { + align-items: center; + display: grid; + gap: 12px; + grid-template-columns: minmax(150px, 26%) minmax(120px, 1fr) 64px 64px; + padding: 4px 0; +} +.ppv-row.with-interval { + grid-template-columns: minmax(150px, 26%) minmax(120px, 1fr) 64px 64px 110px; +} +.ppv-head { + color: var(--color-text-secondary); + font-weight: 500; +} +.ppv-axis { + display: flex; + font-weight: 400; + justify-content: space-between; +} +.ppv-label { + font-weight: 500; + min-width: 0; +} +.ppv-track { + background: #eef1f3; + background-image: linear-gradient(to right, #d8dde1 1px, transparent 1px); + background-position: 50% 0; + background-repeat: no-repeat; + display: block; + height: 16px; +} +.ppv-bar { + display: block; + height: 100%; +} +.num { + font-variant-numeric: tabular-nums; + text-align: right; + white-space: nowrap; +} +@media (max-width: 700px) { + .ppv-row, + .ppv-row.with-interval { + grid-template-columns: 1fr 56px 56px; + } + .ppv-track, + .ppv-axis { + grid-column: 1 / -1; + order: 5; + } +} +.ppv-embedded { + display: block; +} +h3.ppv-title { + font-size: 16px; + font-weight: 500; + margin: 0 0 12px; +} diff --git a/src/app/indicadores/ppv-card.ts b/src/app/indicadores/ppv-card.ts new file mode 100644 index 0000000..8c3fb44 --- /dev/null +++ b/src/app/indicadores/ppv-card.ts @@ -0,0 +1,65 @@ +import { NgTemplateOutlet } from '@angular/common'; +import { Component, computed, input, signal } from '@angular/core'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatCardModule } from '@angular/material/card'; +import { Loading } from '../loading'; +import { Plot } from '../plot'; +import { Reading } from './measures'; +import { ppvDonut, PpvAlternate, PpvMode, PpvRow, ppvRows } from './ppv'; + +/** A positive predictive value in one reading at a time: its score, numerator, denominator and + * interval and what it is and is not stay in view; the buttons choose the whole (a donut) or one + * stratifier of the report (compact bars on a common 0 to 100 % scale, n/N and percent). Every + * measure of this kind can use it by giving its modes. An `alternate` is one more button whose + * view comes from another measure and replaces the whole of the card's own (title, score, note + * and bars), so what is shown always belongs to the measure chosen. */ +@Component({ + selector: 'app-ppv-card', + imports: [Loading, MatButtonToggleModule, MatCardModule, NgTemplateOutlet, Plot], + templateUrl: './ppv-card.html', + styleUrl: './ppv-card.scss', +}) +export class PpvCard { + readonly title = input.required(); + /** what the PPV is and is not (never hidden) */ + readonly note = input(); + /** the score line: "20.0 %" and "3 de 15 pacientes. IC 95 %: …" */ + readonly score = input.required(); + readonly detail = input.required(); + readonly reading = input(); + readonly loading = input(false); + readonly published = input(true); + readonly modes = input.required(); + /** the donut's name for those who confirm */ + readonly confirmed = input('Con histología LIEBG o mayor'); + /** inside another card: no card of its own, and a smaller title */ + readonly embedded = input(false); + /** one more reading, from another measure */ + readonly alternate = input(); + + protected readonly chosen = signal(undefined); + protected readonly selected = computed(() => + this.chosen() === 'alternate' && this.alternate() ? 'alternate' : this.mode().id, + ); + protected readonly mode = computed( + () => this.modes().find((m) => m.id === this.chosen()) ?? this.modes()[0], + ); + protected readonly donut = computed(() => { + const figure = this.mode().figure; + return figure ? figure(this.reading()) : ppvDonut(this.reading(), this.confirmed()); + }); + protected readonly rows = computed(() => { + const { rows, stratum } = this.mode(); + if (rows) return rows(this.reading()); + return stratum ? ppvRows(this.reading(), stratum) : []; + }); + protected hasInterval(rows: PpvRow[]): boolean { + return rows.some((r) => r.low !== undefined); + } + /** No patients: a PPV's denominator, or a cohort's population. */ + protected readonly empty = computed(() => { + const p = this.reading()?.populations ?? {}; + return !(p['denominator'] ?? p['initial-population'] ?? 0); + }); + protected readonly fixed = (n: number) => n.toFixed(1); +} diff --git a/src/app/indicadores/ppv.spec.ts b/src/app/indicadores/ppv.spec.ts new file mode 100644 index 0000000..19289a9 --- /dev/null +++ b/src/app/indicadores/ppv.spec.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { PPV_BIOPSY_MODES, PPV_COLPOSCOPY_MODES, ppvDonut, ppvRows } from './ppv'; +import { Reading } from './measures'; + +const cell = (numerator: number, denominator: number) => ({ + 'initial-population': denominator, + numerator, + denominator, +}); +const report = (strata: Reading['strata'], numerator = 3, denominator = 15): Reading => ({ + populations: { 'initial-population': denominator, numerator, denominator }, + score: numerator / denominator, + strata, +}); + +describe('PPV by group', () => { + it('lists the groups in the page order with n/N and percent, and neutral for no data', () => { + const rows = ppvRows( + report({ + referral_cytology: { + no_data: cell(1, 4), + 'HSIL+': cell(2, 2), + 'ASCUS+': cell(2, 8), + }, + }), + 'referral_cytology', + ); + expect(rows.map((r) => r.code)).toEqual(['ASCUS+', 'HSIL+', 'no_data']); + expect(rows[0]).toMatchObject({ numerator: 2, denominator: 8, percent: 25 }); + expect(rows[1].percent).toBe(100); + expect(rows[2].color).toBe('#C9CDD2'); + // the colours are the cytology ones of the rest of the page + expect(rows[0].color).toBe('#2778B8'); + expect(rows[1].color).toBe('#CE4778'); + }); + + it('keeps a group without patients as no rate (not 0 %) and never invents an absent group', () => { + const rows = ppvRows( + report({ histology_level: { 'LIEBG+': cell(0, 0), 'LIEAG+': cell(0, 4) } }), + 'histology_level', + ); + expect(rows.map((r) => r.code)).toEqual(['LIEBG+', 'LIEAG+']); + expect(rows[0].percent).toBeUndefined(); + expect(rows[1].percent).toBe(0); + expect(ppvRows(report({}), 'screening_round')).toEqual([]); + expect(ppvRows(undefined, 'screening_round')).toEqual([]); + }); + + it('leaves out a cell that does not add up instead of correcting it', () => { + const rows = ppvRows( + report({ screening_round: { initial: cell(5, 4), subsequent: cell(1, 2) } }), + 'screening_round', + ); + expect(rows.map((r) => r.code)).toEqual(['subsequent']); + }); + + it('shows an interval only when the report publishes it for the group', () => { + const r = report({ referral_hpv: { negative: cell(1, 5), positive: cell(2, 4) } }); + r.stratumScores = { referral_hpv: { positive: { median: 0.5, low: 0.15, high: 0.85 } } }; + const rows = ppvRows(r, 'referral_hpv'); + expect(rows[0].low).toBeUndefined(); + expect(rows[1].low).toBeCloseTo(15); + expect(rows[1].high).toBeCloseTo(85); + }); + + it('draws the whole as a donut of those who confirm and the rest, and nothing when it is not whole', () => { + const fig = ppvDonut(report({}), 'Con histología LIEBG o mayor')!; + expect((fig.data[0] as { values: number[] }).values).toEqual([3, 12]); + expect(ppvDonut(report({}, 3, 0), 'x')).toBeUndefined(); + expect(ppvDonut(undefined, 'x')).toBeUndefined(); + }); + + it('declares the five readings of the colposcopy PPV, total first, and says which overlap', () => { + expect(PPV_COLPOSCOPY_MODES.map((m) => m.stratum)).toEqual([ + undefined, + 'referral_cytology', + 'referral_hpv', + 'histology_level', + 'screening_round', + ]); + for (const id of ['cytology', 'hpv', 'histology']) + expect(PPV_COLPOSCOPY_MODES.find((m) => m.id === id)!.caption).toMatch( + /traslapan|excluyentes/, + ); + }); + it('gives the biopsy PPV the same readings with its own denominator', () => { + expect(PPV_BIOPSY_MODES.map((m) => m.id)).toEqual(PPV_COLPOSCOPY_MODES.map((m) => m.id)); + expect(PPV_BIOPSY_MODES[0].caption).toContain('con biopsia reportada'); + expect(PPV_COLPOSCOPY_MODES[0].caption).toContain('con colposcopía registrada'); + expect(PPV_BIOPSY_MODES[1].caption).toBe(PPV_COLPOSCOPY_MODES[1].caption); + }); +}); diff --git a/src/app/indicadores/ppv.ts b/src/app/indicadores/ppv.ts new file mode 100644 index 0000000..3dd76c0 --- /dev/null +++ b/src/app/indicadores/ppv.ts @@ -0,0 +1,197 @@ +import type { Figure } from '../plot'; +import { BIOPSY_REPORTS, CYTOLOGY_REPORTS, HPV_REPORTS } from './cacu-results'; +import { name, Reading } from './measures'; + +/** One way to read a positive predictive value: the whole, or a stratifier of the report. */ +export interface PpvMode { + id: string; + label: string; + /** the report's stratifier (none: the whole, shown as a donut) */ + stratum?: string; + /** what the groups are, and whether they overlap, said under the bars */ + caption: string; + /** the bars when they do not come from a stratifier of the report as a PPV's do */ + rows?: (reading: Reading | undefined) => PpvRow[]; + /** the whole's figure when it is not the PPV donut */ + figure?: (reading: Reading | undefined) => Figure | undefined; + /** the header of the percent column (default "%") */ + percentLabel?: string; +} + +/** One bar: the patients that confirm (or are positive) over the patients of the group, as the + * report counts them. */ +export interface PpvRow { + code: string; + label: string; + color: string; + numerator: number; + denominator: number; + /** none when the group has no patients (a zero rate is not the same) */ + percent?: number; + /** the interval, only when the report publishes it for the group (percent) */ + low?: number; + high?: number; +} + +const NEUTRAL = '#C9CDD2'; +const NEUTRAL_DARK = '#9AA3AB'; +/** The colour a category has elsewhere on the page (cytology, HPV, histology), by its code there. */ +const of = (rows: readonly (readonly [string, string, string])[], code: string) => + rows.find((r) => r[0] === code)![2]; + +/** Colours and order of each stratifier's groups: the page's own for cytology, HPV and + * histology; steel tones for the screening round; neutral for "no data". Colours name a + * category, they are not thresholds. */ +const GROUPS: Record = { + referral_cytology: [ + ['ASCUS+', of(CYTOLOGY_REPORTS, 'ASC-US')], + ['LSIL+', of(CYTOLOGY_REPORTS, 'LSIL')], + ['HSIL+', of(CYTOLOGY_REPORTS, 'HSIL')], + ['no_data', NEUTRAL], + ], + referral_hpv: [ + ['negative', of(HPV_REPORTS, 'negative')], + ['positive', of(HPV_REPORTS, 'positive_other')], + ['hpv_16', of(HPV_REPORTS, 'positive_16')], + ['hpv_18', of(HPV_REPORTS, 'positive_18')], + ['no_data', NEUTRAL], + ], + histology_level: [ + ['LIEBG+', of(BIOPSY_REPORTS, 'LSIL')], + ['LIEAG+', of(BIOPSY_REPORTS, 'HSIL')], + ['invasive', of(BIOPSY_REPORTS, 'carcinoma')], + ], + screening_round: [ + ['initial', '#5F7F9A'], + ['subsequent', '#8FA7BB'], + ['no_data', NEUTRAL], + ], +}; + +const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0; + +/** A stratifier's groups as bars, in the page's order. A group the report does not list is not + * drawn (it is not a zero); a cell that is not whole counts, or whose numerator exceeds its + * denominator, is left out rather than corrected. */ +export function ppvRows(reading: Reading | undefined, stratum: string): PpvRow[] { + const cells = reading?.strata[stratum]; + if (!cells) return []; + const order = GROUPS[stratum] ?? []; + const known = order.map(([code]) => code); + const codes = [ + ...known.filter((c) => c in cells), + ...Object.keys(cells).filter((c) => !known.includes(c)), + ]; + return codes.flatMap((code) => { + const { numerator, denominator } = cells[code]; + if (!whole(numerator) || !whole(denominator) || numerator > denominator) return []; + const score = reading?.stratumScores?.[stratum]?.[code]; + return [ + { + code, + label: name(code), + color: order.find(([c]) => c === code)?.[1] ?? NEUTRAL_DARK, + numerator, + denominator, + percent: denominator ? (100 * numerator) / denominator : undefined, + ...(score?.low !== undefined && score.high !== undefined + ? { low: 100 * score.low, high: 100 * score.high } + : {}), + }, + ]; + }); +} + +/** The whole PPV as a donut: those who confirm, and the rest in a neutral tone. */ +export function ppvDonut(reading: Reading | undefined, confirmed: string): Figure | undefined { + const { numerator, denominator } = reading?.populations ?? {}; + if (!whole(numerator) || !whole(denominator) || !denominator || numerator > denominator) + return undefined; + return { + data: [ + { + type: 'pie', + hole: 0.62, + labels: [confirmed, 'Resto'], + values: [numerator, denominator - numerator], + sort: false, + direction: 'clockwise', + textinfo: 'value+percent', + textposition: 'outside', + marker: { colors: ['#6A8000', NEUTRAL] }, + }, + ], + layout: { + showlegend: true, + margin: { t: 16, r: 8, b: 16, l: 8 }, + legend: { orientation: 'h' }, + }, + }; +} + +/** The readings of a referral PPV (the colposcopy's and the biopsy's publish the same four + * stratifiers). The groups of cytology and histology are cumulative and overlap; the HPV ones + * overlap too (a genotype is also a positive); the rounds do not. `patients` says whose the + * denominator is. */ +const ppvModes = (patients: string): PpvMode[] => [ + { + id: 'total', + label: 'Total', + caption: `Pacientes con histología LIEBG o mayor sobre las pacientes ${patients} en el periodo.`, + }, + { + id: 'cytology', + label: 'Citología previa', + stratum: 'referral_cytology', + caption: + 'Por citología previa asociada por fechas: es una asociación por fechas, no un vínculo clínico. ' + + 'Cada grupo incluye su categoría y las más severas, así que los grupos se traslapan y no son excluyentes. ' + + '«Sin dato»: sin citología previa asociada en los 365 días anteriores.', + }, + { + id: 'hpv', + label: 'VPH previo', + stratum: 'referral_hpv', + caption: + 'Por VPH de la citología previa asociada por fechas (asociación por fechas, no vínculo clínico). ' + + 'Los grupos se traslapan: «Positivo» incluye a quienes son positivas para VPH 16 o 18, y una paciente puede estar en ambos genotipos. ' + + '«Sin dato»: sin resultado de VPH o sin citología previa asociada.', + }, + { + id: 'histology', + label: 'Nivel de histología', + stratum: 'histology_level', + caption: + 'Por nivel de histología confirmado. ' + + 'Tres numeradores distintos sobre el mismo denominador (no son categorías excluyentes): cada nivel incluye los más severos.', + }, + { + id: 'round', + label: 'Ronda de tamizaje', + stratum: 'screening_round', + caption: + 'Por tamizaje inicial o subsecuente. ' + + 'Cada paciente está en un solo grupo. «Sin dato»: sin clasificación de tamizaje inicial o subsecuente.', + }, +]; + +export const PPV_COLPOSCOPY_MODES = ppvModes('con colposcopía registrada'); +export const PPV_BIOPSY_MODES = ppvModes('con biopsia reportada'); + +/** One more reading of a PPV card that comes from another measure (the biopsy requests): it + * brings its own title, heading figures, note and bars, and replaces the card's own while chosen. */ +export interface PpvAlternate { + label: string; + title: string; + score: string; + detail: string; + note?: string; + caption: string; + rows: PpvRow[]; + /** secondary counts, one per line */ + lines: string[]; + /** instead of the bars: why there are none (not published, failed, no records) */ + message?: string; + alert?: boolean; + percentLabel?: string; +} diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index 7a88c15..cabd42c 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -83,16 +83,414 @@ } + + + + + + + + + + + + @for (row of rows; track row.label) { + + + + + + + } + +
{{ first }}MedianaObservacionesQ1–Q3
+ {{ row.label }} + @if (row.median !== undefined) { + + } @else { + Sin mediciones en el periodo + } + {{ row.median === undefined ? '—' : row.median + ' días' }}{{ row.observations ?? '—' }} + {{ row.low === undefined || row.high === undefined ? '—' : row.low + '–' + row.high }} +
+
+ + + @if (!untitled) { +

{{ spec.title }}

+ } + @for (note of spec.notes; track note) { +

{{ note }}

+ } + @if (reports.isLoading()) { + + } @else if (distOf(spec); as d) { +

+ {{ d.total }} {{ spec.unit }} en las categorías de la distribución + @if (d.outside) { + · {{ d.outside }} fuera de ellas + } + @if (d.noData) { + · {{ d.noData }} sin dato + } + · escala de las barras de 0 a {{ d.max }}. +

+ @if (d.hiddenCount) { +

+ Categorías que esta vista no desglosa (genotipificación incompleta, indeterminado o no + clasificable). Total en ellas: {{ d.hiddenCount }} ({{ spec.unit }}), incluido en el total + y en los porcentajes. +

+ } + @if (!d.total) { +

Sin {{ spec.unit }} en el periodo (cero registros, no falta de datos).

+ } + + + + + + + + + + @for (item of d.items; track $index) { + @if (item.kind === 'group') { + + + + } @else { + + + + + + } + } + +
Categoría{{ spec.unit }}%
{{ item.label }} · {{ item.count }}
+ {{ item.label }} + + {{ item.count }}{{ d.total ? ((100 * item.count) / d.total).toFixed(1) + ' %' : '—' }}
+ } @else if (rd(spec.measure)?.error) { + + } @else { +

+ Distribución no disponible para este periodo (la medida no está publicada o su reporte no es + consistente). +

+ } +
+ @switch (section.kind) { @case ('route') { -

{{ section.title }}

- @if (reports.isLoading()) { - - } @else if (routeOf(section); as fig) { - - } @else { -

Sin tiempos publicados en el periodo.

+ + +
+

{{ section.title }}

+ @if (section.modes) { + + Acumulado desde la toma + Por pasos + Desglose por CIE-10 + + } +
+ @if (reports.isLoading()) { + + } @else if (!section.modes || routeMode() === 'sample') { + @let rows = stepRows(section, 'sample'); + @if (rows.some((r) => r.median !== undefined)) { +

+ Mediana desde la toma de muestra hasta cada etapa. Escala: 0 a + {{ routeMax(rows) }} días. Las marcas indican el primer y tercer cuartil. +

+ + } @else { +

Sin tiempos publicados en el periodo.

+ } + } @else if (routeMode() === 'step') { + @let rows = stepRows(section, 'step'); + @if (rows.some((r) => r.median !== undefined)) { +

+ Cada barra es la mediana del tramo, desde cero y por separado; las marcas indican + el primer y tercer cuartil. Escala: 0 a {{ routeMax(rows) }} días. Los tramos + pueden corresponder a poblaciones diferentes, por lo que las medianas no se suman. +

+ + } @else { +

Sin tiempos por tramo publicados en el periodo.

+ } + } @else { + @if (icdOf(section); as icd) { +

+ Desglose exploratorio basado en la asociación temporal existente entre la toma y + la nota de diagnóstico; no confirma un vínculo clínico. +

+ @if (icd.reading?.error) { + + } @else if (!icd.reading) { +

Desglose no disponible en este servidor o periodo.

+ } @else { + @let max = icdMax(icd.rows); +

+ {{ icd.reading.populations['measure-observation'] ?? 0 }} mediciones; escala de + 0 a {{ max }} días. +

+ + + + + + + + + + + @for (row of icd.rows; track row.label) { + + + + + + + } @empty { + + + + } + +
CIE-10 y descripciónMedianaMedicionesQ1–Q3
+ {{ row.label }} + + {{ row.median }} días{{ row.count }}{{ row.low }}–{{ row.high }}
Sin observaciones con código CIE-10 en el periodo.
+ } + } + } +
+
+ } + @case ('results') { + + +

{{ section.title }}

+
+
+

{{ section.cytology.title }}

+ + Distribución general + Por escenario clínico + + @if (cytologyView() === 'general') { + + } @else { + @for (f of section.complement; track f.title) { +
+

+ Los mismos resultados de la distribución citológica, según el estatus de + seguimiento de cada paciente al inicio del periodo; cada barra suma 100 % de + sus pacientes con resultado (n indica cuántas son). +

+ @if (reports.isLoading()) { + + } @else if (figureOf(f); as fig) { + @if (scenarioLegend(f); as legend) { +
    + @for (item of legend; track item.label) { +
  • + + {{ item.label }} +
  • + } +
+ } + + } @else { +

Sin pacientes con resultado en el periodo.

+ } +
+ } + } +
+
+ +
+
+ +
+
+
+
+ } + @case ('confirmation') { + @if (confirmOf(section); as c) { + + +

{{ section.title }}

+

+ No son tasas de referencias emitidas: cuentan procedimientos registrados + (colposcopía o biopsia) o solicitudes de biopsia registradas, y la citología previa + se asocia por fechas. Cada lectura tiene su propio denominador y su umbral + histológico. +

+ + Colposcopía + Biopsia + + @if (confirmView() === 'colposcopy') { + + } @else { + + } +
+
+ } + } + @case ('ppv') { + @if (cardOf(section); as c) { + + } + } + @case ('measure-card') { + @if (cardOf(section); as c) { + + +

{{ c.title }}

+ @if (reports.isLoading()) { + + } @else if (!c.published) { +

Medida no publicada por el servidor.

+ } @else if (c.reading?.error) { + + } @else { +

{{ c.score }} · {{ c.detail }}

+ @if (c.note) { +

{{ c.note }}

+ } + @for (f of c.figures; track f.title) { +

{{ f.title }}

+ + } @empty { +

Sin pacientes en el periodo.

+ } + } +
+
} } @case ('tea-summary') { diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss index f641449..869f647 100644 --- a/src/app/indicadores/tab-indicadores.scss +++ b/src/app/indicadores/tab-indicadores.scss @@ -305,3 +305,166 @@ h2.box-subtitle { margin: 0; } } + +.route-head { + align-items: center; + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + justify-content: space-between; +} +.route-toggle { + flex-wrap: wrap; + max-width: 100%; +} +.route-values summary { + color: var(--color-text-secondary); + cursor: pointer; + padding: var(--space-2) 0; +} +.route-table td { + font-variant-numeric: tabular-nums; +} +.duration-track { + position: relative; +} +.duration-track .bar { + background: #42a77e; +} +.quartile { + background: #17324d; + height: 14px; + position: absolute; + top: -3px; + width: 2px; +} +.distribution { + border-collapse: collapse; + font-size: 13px; + width: 100%; +} +.distribution th { + font-weight: 500; + text-align: left; +} +.distribution td, +.distribution thead th:not(:first-child) { + padding-left: 12px; + text-align: right; + white-space: nowrap; +} +.distribution tbody th { + padding: 5px 0; +} +.distribution .group th { + background: #edf2f4; + font-weight: 600; + padding: 6px 8px; +} +.bar-track { + background: #eef1f3; + display: block; + height: 8px; + margin-top: 3px; +} +.bar { + display: block; + height: 100%; +} +.results-grid .distribution tbody th:has(.distribution-label) { + align-items: center; + display: flex; + gap: 10px; +} +.results-grid .distribution-label { + flex: 0 1 45%; + min-width: 0; +} +.results-grid .bar-track { + flex: 1; + height: 16px; + margin: 0; + min-width: 40px; +} +.measure-score { + font-weight: 500; + margin: var(--space-2) 0; +} +.route-card { + margin-top: 24px; +} +.route-card h3.route-title { + margin-top: 0; +} +.results-grid { + display: grid; + gap: 24px; + grid-template-columns: 1fr; + + section { + min-width: 0; + } + p { + font-size: 13px; + margin: var(--space-2) 0; + } +} +h3.dist-title { + font-size: 16px; + font-weight: 500; + margin: var(--space-3) 0; +} +.results-grid .distribution td { + padding-left: 8px; +} +@media (min-width: 850px) { + .results-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .results-grid .biopsy { + grid-column: 1 / -1; + } +} +.hidden-note { + border-left: 3px solid var(--color-border); + padding-left: 8px; +} +.complement { + margin-top: var(--space-2); +} + +.no-data { + color: var(--color-text-secondary); + display: block; + font-size: 12px; + font-weight: 400; + margin-top: 3px; +} +.cytology-views { + flex-wrap: wrap; + margin: var(--space-2) 0 var(--space-3); + max-width: 100%; +} +.legend { + display: flex; + flex-wrap: wrap; + font-size: 12px; + gap: 4px 14px; + list-style: none; + margin: var(--space-2) 0; + padding: 0; +} +.swatch { + display: inline-block; + height: 10px; + margin-right: 5px; + width: 10px; +} +.confirmation-views { + flex-wrap: wrap; + margin: var(--space-2) 0 var(--space-3); + max-width: 100%; +} +.confirmation-note { + font-size: 13px; +} diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index f815d16..889fc62 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -9,6 +9,7 @@ import type { Measure, MeasureReport } from 'fhir/r4'; import { Fhir, resources } from '../fhir'; import { Figure, Plot } from '../plot'; import { LAYOUTS } from './layout'; +import { distribution, durationMax, durationRows, icdRows, withoutHidden } from './cacu-results'; import { ageShare, ageStack, @@ -17,11 +18,10 @@ import { fill, nestedDonut, rateDots, - routeFigure, scenarioBars, shareDonut, } from './figures'; -import { FigureSpec, Kpi, PAGES, Section } from './pages'; +import { DistSpec, FigureSpec, Kpi, PAGES, Section } from './pages'; import { detail, donut, @@ -31,6 +31,7 @@ import { periodLabel, periods, PeriodType, + PPV_NOTES, reading, Reading, scoring, @@ -38,6 +39,8 @@ import { strataBars, } from './measures'; import { Loading } from '../loading'; +import { PpvCard } from './ppv-card'; +import { requestsAlternate } from './confirmation'; /** The period's indicators: the timeliness KPIs, the screening route, and a card per * clinical measure with its figures. */ @@ -52,6 +55,7 @@ import { Loading } from '../loading'; MatCardModule, MatSelectModule, Plot, + PpvCard, ], templateUrl: './tab-indicadores.html', styleUrl: './tab-indicadores.scss', @@ -67,6 +71,12 @@ export class TabIndicadores { /** The period the figures show (set by Aplicar). */ protected readonly applied = signal(undefined); protected readonly routeView = signal<'sample' | 'step'>('sample'); + /** CaCu's route in three readings: cumulative from the sample, step by step, by ICD-10. */ + /** The confirmation card's perspective. */ + protected readonly confirmView = signal<'colposcopy' | 'biopsy'>('colposcopy'); + /** The cytology column's two readings, one at a time. */ + protected readonly cytologyView = signal<'general' | 'scenario'>('general'); + protected readonly routeMode = signal<'sample' | 'step' | 'icd10'>('sample'); protected readonly layout = computed( () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, @@ -114,11 +124,19 @@ export class TabIndicadores { if (!params.period) return new Map(); const found = await Promise.all( params.measures.map(async (m) => { - const page = await this.fhir.search(params.domain, 'MeasureReport', { - measure: m.id!, - 'reporting-period': params.period, - }); - return [m.name!, reading(resources(page, 'MeasureReport')[0])] as const; + try { + // Never `as-of`: CACU_BIOPSIA_SOLICITUD_CONFIRMACION cannot reconstruct the past. + const page = await this.fhir.search(params.domain, 'MeasureReport', { + measure: m.id!, + 'reporting-period': params.period, + }); + return [m.name!, reading(resources(page, 'MeasureReport')[0])] as const; + } catch (error) { + // A CaCu measure the server cannot serve leaves its own card to say so, not the page. + if (params.domain === 'cacu' && m.name?.startsWith('CACU_')) + return [m.name, { populations: {}, strata: {}, error: true } as Reading] as const; + throw error; + } }), ); return new Map(found); @@ -265,10 +283,91 @@ export class TabIndicadores { return (code && this.byName().get(code)?.title) || ''; } /** A clinical section's route or figures, drawn from the applied period's reports. */ - protected routeOf(section: Section): Figure | undefined { - if (section.kind !== 'route') return undefined; - const steps = section.steps.map((s) => ({ label: s.label, r: this.rd(s.measure) })); - return steps.some((s) => s.r?.score !== undefined) ? routeFigure(steps) : undefined; + /** A route's steps in one reading: days from the sample, or from the previous step. */ + protected routeSteps(section: Section, mode: 'sample' | 'step') { + if (section.kind !== 'route') return []; + return section.steps.map((s) => ({ + label: mode === 'step' ? (s.step ?? s.label) : s.label, + r: this.rd(mode === 'step' ? (s.stepMeasure ?? s.measure) : s.measure), + })); + } + /** The route's table: each step keeps its row, with or without measurements. */ + protected stepRows(section: Section, mode: 'sample' | 'step') { + return durationRows(this.routeSteps(section, mode)); + } + protected icdOf(section: Section) { + return section.kind === 'route' && section.modes + ? { reading: this.rd(section.modes.icd), rows: icdRows(this.rd(section.modes.icd)) } + : undefined; + } + protected icdMax(rows: { median: number; high?: number }[]): number { + return Math.max(0, ...rows.map((r) => Math.max(r.median, r.high ?? 0))); + } + /** A distribution's table: its categories with their group lines, or none when the report + * does not add up (a zero is a zero; a report that is missing or inconsistent is not drawn). + * The categories the spec hides are left out of the rows only: the total, the percentages + * and the units outside stay as the report gives them. */ + protected distOf(spec: DistSpec) { + const d = distribution(this.rd(spec.measure), spec.catalog); + if (!d) return undefined; + const { shown, max, hiddenCount } = withoutHidden(d, spec.hide); + const items = shown.flatMap((row) => [ + ...(spec.groups ?? []) + .filter((g) => g.before === row.code) + .map((g) => ({ + kind: 'group' as const, + label: g.label, + count: d.rows.filter((r) => g.codes.includes(r.code)).reduce((n, r) => n + r.count, 0), + })), + { kind: 'row' as const, ...row }, + ]); + return { + ...d, + items, + max, + hiddenCount, + }; + } + /** The scale of a duration table, in days from zero. */ + protected routeMax = durationMax; + /** The confirmation card: both PPV cards, the requests reading. */ + protected confirmOf(section: Section) { + if (section.kind !== 'confirmation') return undefined; + return { + colposcopy: this.cardOf({ kind: 'ppv', ...section.colposcopy })!, + biopsy: this.cardOf({ kind: 'ppv', ...section.biopsy })!, + requests: requestsAlternate( + this.rd(section.biopsy.requests), + this.byName().has(section.biopsy.requests), + ), + }; + } + /** A measure's card: its title (the PPVs say they are not referrals), score and figures. */ + protected cardOf(section: Section) { + if (section.kind !== 'measure-card' && section.kind !== 'ppv') return undefined; + const m = this.byName().get(section.measure); + const r = this.rd(section.measure); + const summary = section.kind === 'ppv' ? section.summary : undefined; + return { + published: !!m, + reading: r, + title: PPV_NOTES[section.measure]?.title ?? m?.title ?? section.measure, + note: PPV_NOTES[section.measure]?.note, + score: summary ? summary(r).score : m ? formatScore(m, r) : '', + detail: summary ? summary(r).detail : m ? detail(m, r) : '', + figures: this.figureSets().get(section.measure) ?? [], + }; + } + /** The legend of the scenario figure, in the catalogue's order (the figure draws none). */ + protected scenarioLegend(spec: FigureSpec) { + return spec.kind === 'scenario-bars' + ? spec.catalog.categories.map((c) => ({ label: c.label, color: c.color })) + : undefined; + } + /** The scenario figure's height: a slim bar per scenario and room for the axis. */ + protected scenarioHeight(fig: Figure): number { + const bars = (fig.data[0] as { y?: unknown[] } | undefined)?.y?.length ?? 1; + return 70 + bars * 46; } protected figureOf(spec: FigureSpec): Figure | undefined { const r = this.rd(spec.measure); diff --git a/src/app/indicadores/tab-riesgos.html b/src/app/indicadores/tab-riesgos.html index fda4a21..a528489 100644 --- a/src/app/indicadores/tab-riesgos.html +++ b/src/app/indicadores/tab-riesgos.html @@ -1,5 +1,44 @@ +
+ + +
+@if (exportMessage()) { + +} +
+ + Edad mínima + + + + Edad máxima + + + Fecha de corte +@if (invalidAge()) { + +} + @if (error()) {
{{ row.curp }}
} - {{ row.ageGroup }} + + {{ row.age ?? 'No disponible' }} + Grupo: {{ row.ageGroup || 'No disponible' }} + {{ name(row.status) }} + +
+ + +
+ @if (row.cytology; as c) { {{ @@ -154,10 +227,23 @@ {{ latest(row) ?? 'No disponible' }} {{ row.daysToDiagnosis ?? 'No disponible' }} + @if (expanded() === row.patient.id) { + + + + + + } } @empty { @if (page() && !loading()) { - No hay registros para los filtros aplicados. + No hay registros para los filtros aplicados. } } diff --git a/src/app/indicadores/tab-riesgos.scss b/src/app/indicadores/tab-riesgos.scss index ad492df..6665750 100644 --- a/src/app/indicadores/tab-riesgos.scss +++ b/src/app/indicadores/tab-riesgos.scss @@ -60,3 +60,50 @@ a { .window { margin: 4px 0 8px; } + +.export-actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); + justify-content: flex-end; + margin-bottom: var(--space-3); +} + +.stage-compact { + align-items: center; + display: flex; +} + +.stage-toggle { + background: transparent; + border: 0; + color: #385c6c; + cursor: pointer; + display: grid; + flex: 0 0 32px; + height: 32px; + padding: 0; + place-items: center; + width: 32px; +} + +.stage-toggle:focus-visible { + outline: 2px solid #2778b8; + outline-offset: 2px; +} + +.stage-toggle span { + display: block; + font-size: 18px; + line-height: 1; + transition: transform 120ms ease; +} + +.stage-toggle span.open { + transform: rotate(180deg); +} + +// the detailed stages of one patient, across the table +.stage-panel td { + background: var(--mat-sys-surface-container-low, #f6f8f9); +} diff --git a/src/app/indicadores/tab-riesgos.ts b/src/app/indicadores/tab-riesgos.ts index fcf0dea..4a641a6 100644 --- a/src/app/indicadores/tab-riesgos.ts +++ b/src/app/indicadores/tab-riesgos.ts @@ -1,4 +1,5 @@ import { DecimalPipe } from '@angular/common'; +import { HttpClient } from '@angular/common/http'; import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; @@ -7,16 +8,25 @@ import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { RouterLink } from '@angular/router'; import type { Bundle } from 'fhir/r4'; +import { firstValueFrom } from 'rxjs'; +import { downloadDocument } from '../export-document'; import { Fhir } from '../fhir'; -import { Row, rows, windowStart } from './follow-up'; -import { PatientSearch, patientSearch } from './patient-search'; import { Loading } from '../loading'; +import { Stages, stages } from '../paciente/stages'; +import { patientLabel, Row, rows, windowStart } from './follow-up'; import { name } from './measures'; +import { PatientSearch, patientSearch } from './patient-search'; const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']; +const SORTS: Record = { + '-recent': 'Estudio más reciente', + '-risk-cin2': 'Mayor riesgo de LIEAG+', + '-risk-cancer': 'Mayor riesgo de cáncer', +}; -/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status, - * results and current risks, in the order asked for. */ +/** CaCu's follow-up list at a cut-off: who had a cytology in the window, her age, status, the + * stages of her screening, results and current risks, in the order asked for; and the same + * query as a PDF or an Excel file. */ @Component({ selector: 'app-tab-riesgos', imports: [ @@ -29,12 +39,14 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'] MatInputModule, MatSelectModule, RouterLink, + Stages, ], templateUrl: './tab-riesgos.html', styleUrl: './tab-riesgos.scss', }) export class TabRiesgos { private readonly fhir = inject(Fhir); + private readonly http = inject(HttpClient); readonly domain = input.required(); protected readonly cutoff = signal(''); @@ -45,17 +57,42 @@ export class TabRiesgos { protected readonly size = signal(20); /** "Buscar paciente": her name, CURP or record number, as applied. */ protected readonly search = signal(''); + /** Completed years at the cut-off, from and to (none: no limit). */ + protected readonly ageMin = signal(null); + protected readonly ageMax = signal(null); + /** The patient whose stages are open under her row. */ + protected readonly expanded = signal(undefined); /** A page the user moved to (`next`/`previous`), else the first. */ private readonly moved = signal(undefined); + protected readonly exporting = signal(false); + protected readonly exportMessage = signal(''); protected readonly statuses = STATUSES; protected readonly name = name; + protected readonly patientLabel = patientLabel; + + /** Whole years between 0 and 150, and the minimum not above the maximum; else the range is + * not applied and the page says so. */ + protected readonly invalidAge = computed(() => { + const [low, high] = [this.ageMin(), this.ageMax()]; + const bad = (n: number | null) => n !== null && (!Number.isInteger(n) || n < 0 || n > 150); + return bad(low) || bad(high) || (low !== null && high !== null && low > high); + }); + private readonly ages = computed(() => + this.invalidAge() + ? {} + : { + 'follow-up-age-min': this.ageMin() ?? undefined, + 'follow-up-age-max': this.ageMax() ?? undefined, + }, + ); private readonly first = resource({ params: () => ({ domain: this.domain(), 'follow-up-window': this.window(), ...patientSearch(this.search()), + ...this.ages(), 'follow-up-cutoff': this.cutoff() || undefined, 'follow-up-status': this.status() || undefined, 'risk-horizon': this.horizon(), @@ -64,6 +101,7 @@ export class TabRiesgos { }), loader: ({ params: { domain, ...params } }) => { this.moved.set(undefined); + this.expanded.set(undefined); return this.fhir.search(domain, 'Patient', { ...params, _revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'], @@ -112,6 +150,13 @@ export class TabRiesgos { protected retry(): void { this.first.reload(); } + protected toggle(id: string | undefined): void { + this.expanded.set(this.expanded() === id ? undefined : id); + } + protected clearAges(): void { + this.ageMin.set(null); + this.ageMax.set(null); + } protected has(relation: 'next' | 'previous'): boolean { return !!this.page()?.link?.some((l) => l.relation === relation); @@ -128,4 +173,145 @@ export class TabRiesgos { this.loading.set(false); } } + + /** What an export may not start from: no list yet, a range not applied, or a query in motion. */ + protected readonly cannotExport = computed( + () => + this.exporting() || + !this.page() || + this.invalidAge() || + this.first.isLoading() || + this.loading(), + ); + + /** The whole query (not the page on screen) as a PDF or an Excel file, with the filters it + * was asked with. The server's limits are the ones that decide; the list is read again + * whole and must still be the query it was when the button was pressed. */ + protected async exportList(format: 'xlsx' | 'pdf'): Promise { + if (this.cannotExport() || !this.applied()) return; + const total = this.page()!.total ?? 0; + const cutoff = this.applied(); + const months = this.window(); + const horizon = this.horizon(); + this.exporting.set(true); + this.exportMessage.set(''); + try { + const limits = await firstValueFrom( + this.http.get<{ xlsx_limit: number; pdf_limit: number }>('/api/cacu/exports/capabilities'), + ); + const limit = format === 'pdf' ? limits.pdf_limit : limits.xlsx_limit; + if (total > limit) { + this.exportMessage.set( + `La consulta tiene ${total} pacientes; el límite para ${format.toUpperCase()} es ${limit}. Ajuste los filtros.`, + ); + return; + } + const params = { + 'follow-up-window': months, + 'follow-up-cutoff': cutoff, + 'follow-up-status': this.status() || undefined, + 'risk-horizon': horizon, + _sort: this.sort(), + _count: 200, + ...patientSearch(this.search()), + ...this.ages(), + _revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'], + '_include:iterate': 'DiagnosticReport:result', + }; + const pages = await this.fhir.all(this.domain(), 'Patient', params); + const all = pages.flatMap((p) => rows(p, windowStart(cutoff, months), cutoff, horizon)); + if ( + all.length !== total || + new Set(all.map((r) => r.patient.id)).size !== total || + pages.some((p) => p.total !== total) + ) + throw new Error('La consulta cambió durante la exportación; vuelva a intentarlo.'); + await downloadDocument(this.http, format, this.document(all, cutoff, months, horizon, total)); + } catch (error) { + this.exportMessage.set( + error instanceof Error ? error.message : 'No se pudo generar la exportación.', + ); + } finally { + this.exporting.set(false); + } + } + + /** The document: the parameters of the query and one row per patient, as the list shows her. */ + private document(all: Row[], cutoff: string, months: number, horizon: number, total: number) { + const pct = (n?: number) => (n === undefined ? 'No disponible' : `${(100 * n).toFixed(1)} %`); + const years = `${horizon} ${horizon === 1 ? 'año' : 'años'}`; + const routes = all.map((r) => + stages( + r.cytology?.date, + r.cytology?.result ? r.cytology.reportDate : undefined, + cutoff, + r.stageFacts, + ), + ); + return { + title: 'Resultados de seguimiento', + parameters: [ + ['Fecha de corte', cutoff], + [ + 'Ventana consultada', + `${windowStart(cutoff, months)} al ${cutoff} (${months} ${months === 1 ? 'mes' : 'meses'})`, + ], + ['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'], + ['Orden', SORTS[this.sort()] ?? this.sort()], + ['Horizonte de la probabilidad', years], + ['Nombre o identificador', this.search().trim() || 'Todos'], + ['Edad mínima (años)', String(this.ageMin() ?? 'Sin límite')], + ['Edad máxima (años)', String(this.ageMax() ?? 'Sin límite')], + ['Registros', String(total)], + ], + columns: [ + 'Paciente', + 'Edad', + 'Estatus', + 'Etapas', + 'Última citología', + 'VPH', + 'Biopsia', + `Riesgo LIEAG+ a ${years}`, + `Riesgo de cáncer a ${years}`, + 'Días de toma a diagnóstico', + ], + row_stages: routes.map((route) => + route.map((s) => ({ + state: s.state, + ...(s.provenance ? { provenance: s.provenance } : {}), + ...(s.date ? { date: s.date } : {}), + })), + ), + rows: all.map((r, i) => [ + `${patientLabel(r.patient)}${r.curp ? '\n' + r.curp : ''}`, + r.age === undefined ? 'No disponible' : `${r.age}`, + name(r.status), + routes[i] + .map( + (s) => + `${s.label}: ${s.state}${s.date ? ' ' + s.date : ''}${s.provenance ? ' (' + s.provenance + ')' : ''}`, + ) + .join('\n'), + r.cytology + ? `${r.cytology.date} · ${ + r.cytology.result + ? name(r.cytology.result) + : r.cytology.adequacy === 'unsatisfactory' + ? 'Insatisfactoria' + : 'Pendiente' + }` + : 'No disponible', + r.hpv + ? `${r.hpv.positive ? 'Positivo' : 'Negativo'}${r.hpv.types1618 ? ' (16/18)' : ''}` + : 'No disponible', + r.biopsy + ? `${r.biopsy.date} · ${name(r.biopsy.histology ?? '') || 'Sin grado'}` + : 'No disponible', + pct(r.risk.cin2), + pct(r.risk.cancer), + String(r.daysToDiagnosis ?? 'No disponible'), + ]), + }; + } } diff --git a/src/app/indicadores/vph.spec.ts b/src/app/indicadores/vph.spec.ts new file mode 100644 index 0000000..7dfc863 --- /dev/null +++ b/src/app/indicadores/vph.spec.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from 'vitest'; +import { Reading } from './measures'; +import { VPH_MODES, vphDonut, vphGenotypes, vphGroups, vphSummary } from './vph'; + +const n = (count: number) => ({ 'initial-population': count }); +const report = (strata: Reading['strata'], population = 10): Reading => ({ + populations: { 'initial-population': population }, + strata, +}); +const base = { category: { negative: n(7), positive: n(3) } }; + +describe('CACU_VPH readings (patients by their latest HPV result)', () => { + it('summarises the patients and how they split, and does not invent when it does not add up', () => { + expect(vphSummary(report(base))).toEqual({ + score: '10 pacientes', + detail: 'Negativo: 7 (70.0 %) · Positivo: 3 (30.0 %).', + }); + expect(vphSummary(report({ category: { negative: n(7) } })).score).toBe('Sin dato'); + expect(vphSummary(undefined).score).toBe('Sin dato'); + // a real zero is a zero, not a missing report + expect(vphSummary(report({ category: {} }, 0)).score).toBe('0 pacientes'); + expect(vphDonut(report({ category: {} }, 0))).toBeUndefined(); + }); + + it('draws the whole as negative and positive in the HPV colours of the page', () => { + const fig = vphDonut(report(base))!; + const pie = fig.data[0] as { values: number[]; marker: { colors: string[] } }; + expect(pie.values).toEqual([7, 3]); + expect(pie.marker.colors).toEqual(['#42a77e', '#a8c243']); + }); + + it('gives each group its positives over its patients with a result, in age order', () => { + const rows = vphGroups( + report({ + ...base, + 'age_group-category': { + '45-54|positive': n(2), + '45-54|negative': n(2), + '25-34|negative': n(4), + '<25|positive': n(1), + }, + }), + 'age_group', + ); + expect(rows.map((r) => r.code)).toEqual(['<25', '25-34', '45-54']); + expect(rows[2]).toMatchObject({ numerator: 2, denominator: 4, percent: 50 }); + // a group with patients and no positive is a zero rate, not a missing one + expect(rows[1]).toMatchObject({ numerator: 0, denominator: 4, percent: 0 }); + expect(vphGroups(report(base), 'age_group')).toEqual([]); + }); + + it('keeps "no data" neutral and the rounds excluding', () => { + const rows = vphGroups( + report({ + ...base, + 'screening_round-category': { + 'no_data|negative': n(1), + 'initial|positive': n(1), + 'subsequent|negative': n(2), + }, + }), + 'screening_round', + ); + expect(rows.map((r) => r.code)).toEqual(['initial', 'subsequent', 'no_data']); + expect(rows[2]).toMatchObject({ label: 'Sin dato', color: '#C9CDD2' }); + }); + + it('reads each genotype over the patients whose genotype was reported, and skips an unpublished one', () => { + const rows = vphGenotypes(report({ ...base, hpv_16: { negative: n(5), positive: n(2) } })); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + label: 'VPH 16', + numerator: 2, + denominator: 7, + color: '#df8640', + }); + }); + + it('offers the whole and the four breakdowns the measure publishes', () => { + expect(VPH_MODES.map((m) => m.id)).toEqual(['total', 'age', 'status', 'genotype', 'round']); + expect(VPH_MODES.every((m) => m.caption.length > 20)).toBe(true); + }); +}); diff --git a/src/app/indicadores/vph.ts b/src/app/indicadores/vph.ts new file mode 100644 index 0000000..2783b48 --- /dev/null +++ b/src/app/indicadores/vph.ts @@ -0,0 +1,187 @@ +import type { Figure } from '../plot'; +import { HPV_REPORTS } from './cacu-results'; +import { name, Reading } from './measures'; +import { PpvMode, PpvRow } from './ppv'; + +/** CACU_VPH counts patients: each one by her latest sample with an HPV result in the period. It + * is not CACU_VPH_GENOTIPO, which counts reports. Its readings are the ones the report publishes: + * the result (the `category` stratum), that result inside each group of a stratifier (the report's + * `-category` cells), and the genotypes 16 and 18 (strata of their own). */ +const color = (code: string) => HPV_REPORTS.find((r) => r[0] === code)![2]; +const NEGATIVE = color('negative'); +const POSITIVE = color('positive_other'); +const NEUTRAL = '#C9CDD2'; +const STEEL = '#5F7F9A'; + +const whole = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0; +const count = (cell: Record | undefined) => cell?.['initial-population']; + +/** The patients by result, when the report adds up to its population. */ +function results(reading: Reading | undefined) { + const cells = reading?.strata['category']; + const total = reading?.populations['initial-population']; + if (!cells || !whole(total)) return undefined; + const negative = count(cells['negative']) ?? 0; + const positive = count(cells['positive']) ?? 0; + const other = Object.keys(cells).some((c) => c !== 'negative' && c !== 'positive'); + return whole(negative) && whole(positive) && !other && negative + positive === total + ? { total, negative, positive } + : undefined; +} + +const share = (n: number, of: number) => ((100 * n) / of).toFixed(1); + +/** The card's heading figures: patients with a result, and how they split. */ +export function vphSummary(reading: Reading | undefined): { score: string; detail: string } { + const r = results(reading); + if (!r) return { score: 'Sin dato', detail: '' }; + if (!r.total) return { score: '0 pacientes', detail: 'Sin pacientes en el periodo.' }; + return { + score: `${r.total} pacientes`, + detail: `Negativo: ${r.negative} (${share(r.negative, r.total)} %) · Positivo: ${r.positive} (${share(r.positive, r.total)} %).`, + }; +} + +/** The whole: negative and positive patients as a donut. */ +export function vphDonut(reading: Reading | undefined): Figure | undefined { + const r = results(reading); + if (!r?.total) return undefined; + return { + data: [ + { + type: 'pie', + hole: 0.62, + labels: ['Negativo', 'Positivo'], + values: [r.negative, r.positive], + sort: false, + direction: 'clockwise', + textinfo: 'value+percent', + textposition: 'outside', + marker: { colors: [NEGATIVE, POSITIVE] }, + }, + ], + layout: { + showlegend: true, + margin: { t: 16, r: 8, b: 16, l: 8 }, + legend: { orientation: 'h' }, + }, + }; +} + +const AGES = ['<25', '25-34', '35-44', '45-54', '55-64', '65+']; +const ORDER: Record = { + age_group: AGES.map((c) => [c, STEEL]), + follow_up_status: [ + ['pre_colposcopy', STEEL], + ['post_colposcopy', '#8FA7BB'], + ['post_treatment', '#B5C5D3'], + ['case', '#9AA3AB'], + ], + screening_round: [ + ['initial', STEEL], + ['subsequent', '#8FA7BB'], + ['no_data', NEUTRAL], + ], +}; + +const groupLabel = (group: string) => + group === 'no_data' + ? 'Sin dato' + : name(group) === group + ? group.replace('-', ' a ') + : name(group); + +/** A group's positive patients over its patients with a result, from the report's crossed cells. + * A group the report does not list is not drawn; absent is not a zero. */ +export function vphGroups(reading: Reading | undefined, stratum: string): PpvRow[] { + const cells = reading?.strata[`${stratum}-category`]; + if (!cells) return []; + const groups = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))]; + const order = ORDER[stratum] ?? []; + const known = order.map(([c]) => c); + return [...known.filter((g) => groups.includes(g)), ...groups.filter((g) => !known.includes(g))] + .map((group) => { + const negative = count(cells[`${group}|negative`]) ?? 0; + const positive = count(cells[`${group}|positive`]) ?? 0; + const denominator = negative + positive; + return { + code: group, + label: groupLabel(group), + color: order.find(([c]) => c === group)?.[1] ?? STEEL, + numerator: positive, + denominator, + percent: denominator ? (100 * positive) / denominator : undefined, + }; + }) + .filter((row) => whole(row.numerator) && whole(row.denominator)); +} + +/** Genotype 16 and 18: positives over the patients whose genotype was reported (its own stratum). */ +export function vphGenotypes(reading: Reading | undefined): PpvRow[] { + return ( + [ + ['hpv_16', 'VPH 16', color('positive_16')], + ['hpv_18', 'VPH 18', color('positive_18')], + ] as const + ).flatMap(([stratum, label, tone]) => { + const cells = reading?.strata[stratum]; + if (!cells) return []; + const negative = count(cells['negative']) ?? 0; + const positive = count(cells['positive']) ?? 0; + if (!whole(negative) || !whole(positive)) return []; + const denominator = negative + positive; + return [ + { + code: stratum, + label, + color: tone, + numerator: positive, + denominator, + percent: denominator ? (100 * positive) / denominator : undefined, + }, + ]; + }); +} + +const POSITIVES = '% positivas'; +const OF_RESULT = 'Positivas sobre las pacientes con resultado de VPH del grupo (n/N)'; + +/** The readings of CACU_VPH: the whole, and each breakdown the measure publishes. */ +export const VPH_MODES: PpvMode[] = [ + { + id: 'total', + label: 'Total', + figure: vphDonut, + caption: + 'Una paciente por periodo, por su última muestra con resultado de VPH: negativas y positivas sobre todas ellas.', + }, + { + id: 'age', + label: 'Por grupo de edad', + rows: (r) => vphGroups(r, 'age_group'), + percentLabel: POSITIVES, + caption: `${OF_RESULT}. Los grupos son excluyentes.`, + }, + { + id: 'status', + label: 'Por estatus de seguimiento', + rows: (r) => vphGroups(r, 'follow_up_status'), + percentLabel: POSITIVES, + caption: `${OF_RESULT}. El estatus es el de la paciente al inicio del periodo; los grupos son excluyentes.`, + }, + { + id: 'genotype', + label: 'Por genotipo', + rows: vphGenotypes, + percentLabel: POSITIVES, + caption: + 'Positivas para el genotipo sobre las pacientes con ese genotipo reportado; el denominador cambia por genotipo y una paciente puede ser positiva para ambos.', + }, + { + id: 'round', + label: 'Por tamizaje inicial o subsecuente', + rows: (r) => vphGroups(r, 'screening_round'), + percentLabel: POSITIVES, + caption: `${OF_RESULT}. Cada paciente está en un solo grupo; «Sin dato»: sin clasificación de tamizaje inicial o subsecuente.`, + }, +]; diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index 2e58f4b..c7d92a2 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -1,4 +1,14 @@
+ @if (domain() === 'cacu' && patient()) { +
+ +
+ } + @if (exportError()) { + + } arrow_back Regresar @@ -7,6 +17,9 @@ } @else if (patient(); as p) {

{{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} + @if (domain() === 'cacu') { + · Edad: {{ age() ?? 'No disponible' }} + }

@@ -104,6 +117,20 @@ Historial médico + @if (domain() === 'cacu') { + +

+ Etapas de la citología{{ sample() ? ' del ' + sample() : '' }} a la fecha de corte + {{ cutoff() }}. «Inferida temporalmente» es una asociación por cercanía de fechas, no + un vínculo clínico confirmado; «Desconocida» indica que no hay dato. +

+ } @@ -169,6 +196,72 @@ >Riesgos y recomendaciones + @if (domain() === 'cacu') { +

+ Divisiones numéricas descriptivas; no representan umbrales clínicos. +

+ @for (model of riskScales(); track model.model) { +

{{ model.model }} · fecha índice {{ model.index }}

+ @for ( + scale of [ + { label: 'Riesgo inmediato (al índice)', value: model.immediate }, + { label: 'Riesgo a 5 años', value: model.five }, + ]; + track scale.label + ) { +
+

+ {{ scale.label }} + @if (scale.value; as v) { + @if (v.low !== undefined && v.high !== undefined) { + · IC 95 %: {{ v.low * 100 | number: '1.1-2' }}–{{ + v.high * 100 | number: '1.1-2' + }} + % + } + } @else { + · No disponible + } +

+
+ + @if (scale.value; as v) { + + {{ v.value * 100 | number: '1.1-2' }} % + } +
+
+ 0 %25 %50 %75 %100 % +
+
+ } + } @empty { + @for (label of ['Riesgo inmediato', 'Riesgo a 5 años']; track label) { +
+

+ {{ label }} · No disponible +

+
+ +
+
+ 0 %25 %50 %75 %100 % +
+
+ } +

Ningún modelo vigente la ha evaluado.

+ } + } @if (models().length) {
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index 23a5a44..857534b 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -98,3 +98,69 @@ h1 .id { margin-left: var(--space-2); vertical-align: middle; } + +.export-actions { + display: flex; + justify-content: flex-end; + margin-bottom: var(--space-3); +} + +.route-note { + font-size: 12px; + margin: var(--space-2) 0 var(--space-3); +} + +// the risk scale: four equal numeric parts of 0 to 100 %, descriptive, not clinical thresholds +.risk-scale { + margin: 8px 0 14px; + max-width: 740px; + + p { + margin: 0; + } +} +.risk-plot { + padding-top: 24px; + position: relative; +} +.risk-line { + background: linear-gradient( + to right, + #42a77e 0 25%, + #a8c243 25% 50%, + #df8640 50% 75%, + #c24269 75% 100% + ); + height: 16px; +} +.unavailable .risk-line { + background: repeating-linear-gradient( + to right, + #d9dfe2 0, + #d9dfe2 calc(25% - 1px), + #fff calc(25% - 1px), + #fff 25% + ); +} +.risk-marker { + background: #17324d; + bottom: -2px; + height: 20px; + position: absolute; + transform: translateX(-50%); + width: 3px; +} +.risk-value { + color: #17324d; + font-size: 13px; + position: absolute; + top: 1px; + transform: translateX(-50%); + white-space: nowrap; +} +.risk-labels { + display: flex; + font-size: 12px; + justify-content: space-between; + margin-top: 3px; +} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index 60ea35e..86668a1 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -1,4 +1,5 @@ import { DecimalPipe } from '@angular/common'; +import { HttpClient } from '@angular/common/http'; import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; @@ -12,6 +13,7 @@ import type { Procedure, RiskAssessment, } from 'fhir/r4'; +import { firstValueFrom } from 'rxjs'; import { Api } from '../api/api'; import { studies as eegStudies } from '../api/fn/eeg/studies'; import { study as eegStudy } from '../api/fn/eeg/study'; @@ -19,7 +21,16 @@ import { readReport$Json } from '../api/fn/models/read-report-json'; import type { Domain } from '../api/models/domain'; import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { scenarioFigure } from '../gobernanza/figures'; -import { ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; +import { downloadDocument } from '../export-document'; +import { + ageGroup, + CAMA_AGE_GROUPS, + camaRows, + CURP, + exactAge, + patientLabel, + patientName, +} from '../indicadores/follow-up'; import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { BIOMARKER_NAMES, @@ -34,6 +45,8 @@ import type { Relation } from '../api/models/relation'; import { Figure, PALETTE, Plot } from '../plot'; import { Loading } from '../loading'; import { Factores, ScenarioFactors } from './factores'; +import { horizonRisk } from './risk-scale'; +import { daysBetween, intervalText, routeFacts, stages, Stages } from './stages'; /** An Observation's value as the screens say it, whatever its type. */ function shown(o: Observation): string { @@ -54,6 +67,7 @@ function shown(o: Observation): string { imports: [ Factores, Loading, + Stages, DecimalPipe, MatButtonModule, MatCardModule, @@ -72,16 +86,34 @@ export class Paciente { /** The follow-up list she was opened from: its window (months) and cut-off. */ readonly ventana = input(); readonly corte = input(); + /** CaCu: the sample (its day) whose route the list showed. */ + readonly muestra = input(); + private readonly http = inject(HttpClient); + protected readonly exporting = signal(false); + protected readonly exportError = signal(''); private readonly data = resource({ - params: () => ({ domain: this.domain(), id: this.id() }), - loader: async ({ params: { domain, id } }) => { + params: () => ({ domain: this.domain(), id: this.id(), cutoff: this.corte() }), + loader: async ({ params: { domain, id, cutoff } }) => { const subject = { subject: `Patient/${id}`, _count: 200 }; + const cacu = domain === 'cacu' && !!cutoff; const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([ - this.fhir.read(domain, 'Patient', id), + // opened from the list: her status and age as of its cut-off + cacu + ? this.fhir + .search(domain, 'Patient', { _id: id, 'follow-up-cutoff': cutoff }) + .then((bundle) => { + const found = resources(bundle, 'Patient', 'match')[0]; + if (!found) throw new Error('Paciente no encontrada'); + return found; + }) + : this.fhir.read(domain, 'Patient', id), this.fhir.all(domain, 'Condition', subject), this.fhir.all(domain, 'Procedure', subject), - this.fhir.all(domain, 'DiagnosticReport', subject), + this.fhir.all(domain, 'DiagnosticReport', { + ...subject, + 'stage-cutoff': cacu ? cutoff : undefined, + }), this.fhir.all(domain, 'Observation', subject), this.fhir.all(domain, 'RiskAssessment', subject), ]); @@ -387,10 +419,154 @@ export class Paciente { } protected readonly name = name; protected readonly levelNames = LEVEL_NAMES; + + // ---- CaCu: the screening route of one cytology, her age, and her risks ---- + /** The cut-off her route and age are told at: the list's, else today. */ + protected readonly cutoff = computed(() => this.corte() ?? new Date().toISOString().slice(0, 10)); + protected readonly age = computed(() => exactAge(this.patient()?.birthDate, this.cutoff())); + /** The cytology whose route is drawn: the one the list opened her at, else her latest. */ + private readonly routeReport = computed(() => { + const cytologies = (this.data.value()?.reports ?? []).filter( + (r) => code(r.code) === 'cervical_cytology', + ); + return ( + cytologies.find((r) => r.effectiveDateTime === this.muestra()) ?? + (this.muestra() ? undefined : cytologies[0]) + ); + }); + protected readonly sample = computed(() => this.routeReport()?.effectiveDateTime); + /** Her report day, only when the cytology has a result. */ + protected readonly sampleReportDate = computed(() => { + const d = this.data.value(); + const report = this.routeReport(); + const hasResult = (report?.result ?? []).some((ref) => { + const o = d?.observations.get(ref.reference?.split('/')[1]); + return code(o?.code) === 'cervical_cytology.result' && !!code(o?.valueCodeableConcept); + }); + return hasResult ? ext(report, 'report-date')?.valueDate : undefined; + }); + protected readonly sampleFacts = computed(() => routeFacts(this.routeReport())); + /** The route as drawn, for the export too. */ + protected readonly route = computed(() => + stages(this.sample(), this.sampleReportDate(), this.cutoff(), this.sampleFacts()), + ); + /** The immediate (index) and five-year risk of each CaCu risk model, by the horizons the + * model published: a horizon it did not publish is absent, never a zero. The title is the + * model's own, so the outcome is the one it predicts. */ + protected readonly riskScales = computed(() => { + const latest = new Map(); + for (const risk of this.data.value()?.risks ?? []) { + const key = code(risk.method) ?? ''; + if (!key.startsWith('cacu.cin2') && !key.startsWith('cacu.cancer')) continue; + const known = latest.get(key); + if (!known || (known.occurrenceDateTime ?? '') < (risk.occurrenceDateTime ?? '')) + latest.set(key, risk); + } + return [...latest.entries()].map(([model, risk]) => ({ + model: risk.method?.coding?.[0]?.display ?? risk.method?.text ?? model, + index: risk.occurrenceDateTime, + immediate: horizonRisk(risk, 0), + five: horizonRisk(risk, 5), + })); + }); + protected readonly daysBetween = daysBetween; + + /** Her file as a PDF: identity, the route, history, tests and the risk scales, as on screen. */ + protected async exportPatient(): Promise { + const patient = this.patient(); + if (!patient) return; + this.exporting.set(true); + this.exportError.set(''); + try { + await firstValueFrom(this.http.get('/api/cacu/exports/capabilities')); + const route = this.route(); + const inferred = (s?: { provenance?: string }) => s?.provenance === 'Inferida temporalmente'; + const timeline = route.map((s, i) => ({ + state: s.state, + label: s.label, + ...(s.provenance ? { provenance: s.provenance } : {}), + ...(s.date ? { date: s.date } : {}), + prev: intervalText( + i ? route[i - 1].date : undefined, + s.date, + inferred(s) || (i > 0 && inferred(route[i - 1])), + ), + start: intervalText(route[0].date, s.date, inferred(s)), + })); + const lines = (s: (typeof route)[number], i: number) => + `${s.label}: ${s.state}${s.provenance ? ' · ' + s.provenance : ''}; fecha ${s.date ?? '—'}; ` + + `desde anterior ${timeline[i].prev}; desde toma ${timeline[i].start}`; + const entries: string[][] = [ + ['Identificador', patient.id ?? 'No disponible'], + ['Paciente', patientLabel(patient)], + ['CURP', this.identity().curp ?? 'No disponible'], + ['Expedientes', this.identity().numbers.join(', ') || 'No disponible'], + ['Nacimiento', patient.birthDate ?? 'No disponible'], + ['Edad al corte', String(this.age() ?? 'No disponible')], + ['Estatus', this.status() || 'No disponible'], + ...route.map((s, i) => ['Etapa', lines(s, i)]), + ...this.history().map((h) => [ + 'Historial', + `${h.date} · ${h.kind} · ${h.text}${h.code && h.code !== h.text ? ' (' + h.code + ')' : ''}`, + ]), + ...this.tests().map((t) => [ + 'Pruebas', + `${t.date} · ${t.kind} · ${t.reported ?? 'Pendiente'} · ${t.results.join(' · ') || '—'}`, + ]), + ]; + const percent = (n: number) => `${(n * 100).toFixed(2)} %`; + const scale = (model: string, horizon: string, v: ReturnType) => ({ + label: `${model} · ${horizon}: ${v ? percent(v.value) : 'No disponible'}`, + outcome: model, + model, + horizon, + ...(v + ? { + value: v.value, + ...(v.low !== undefined && v.high !== undefined ? { low: v.low, high: v.high } : {}), + } + : {}), + }); + const scales = this.riskScales().flatMap((r) => [ + scale(r.model, 'Inmediato', r.immediate), + scale(r.model, '5 años', r.five), + ]); + for (const s of scales) entries.push(['Riesgo', s.label]); + if (!scales.length) + entries.push(['Riesgo', 'Inmediato: No disponible · 5 años: No disponible']); + await downloadDocument(this.http, 'pdf', { + title: 'Ficha individual', + parameters: [ + ['Corte (edad, estatus y etapas)', this.cutoff()], + [ + 'Historial y riesgos', + 'Información longitudinal disponible; no filtrada por corte histórico', + ], + ], + columns: ['Sección', 'Información'], + rows: entries, + timeline, + risk_scales: scales.length + ? scales + : [ + { label: 'Riesgo inmediato: No disponible' }, + { label: 'Riesgo a 5 años: No disponible' }, + ], + }); + } catch (error) { + this.exportError.set( + error instanceof Error + ? `No se pudo generar la ficha PDF: ${error.message}` + : 'No se pudo generar la ficha PDF.', + ); + } finally { + this.exporting.set(false); + } + } protected readonly identity = computed(() => { const p = this.patient(); return { - name: p?.name?.[0]?.text, + name: patientName(p), curp: p?.identifier?.find((i) => i.system === CURP)?.value, // each record number once (several sources may carry the same one) numbers: [ diff --git a/src/app/paciente/risk-scale.ts b/src/app/paciente/risk-scale.ts new file mode 100644 index 0000000..d2e76ee --- /dev/null +++ b/src/app/paciente/risk-scale.ts @@ -0,0 +1,24 @@ +import type { RiskAssessment } from 'fhir/r4'; + +/** Only an explicitly published horizon is eligible; zero remains a real value. */ +export function horizonRisk(risk: RiskAssessment, years: number) { + const p = (risk.prediction ?? []).find( + (x) => + x.whenRange?.high?.value === years && + x.whenRange.high.code === 'a' && + x.probabilityDecimal !== undefined && + x.probabilityDecimal >= 0 && + x.probabilityDecimal <= 1, + ); + if (!p) return undefined; + const value = p.probabilityDecimal!; + const get = (suffix: string) => + p.extension?.find((e) => e.url.endsWith('/' + suffix))?.valueDecimal; + const low = get('ic-bajo'), + high = get('ic-alto'); + return { + value, + low: low !== undefined && low >= 0 && low <= 1 ? low : undefined, + high: high !== undefined && high >= 0 && high <= 1 ? high : undefined, + }; +} diff --git a/src/app/paciente/stages-risk.spec.ts b/src/app/paciente/stages-risk.spec.ts new file mode 100644 index 0000000..b6dc2dc --- /dev/null +++ b/src/app/paciente/stages-risk.spec.ts @@ -0,0 +1,54 @@ +import '@angular/compiler'; +import { describe, expect, it } from 'vitest'; +import type { RiskAssessment } from 'fhir/r4'; +import { daysBetween, intervalText, stages } from './stages'; +import { horizonRisk } from './risk-scale'; + +describe('stages and explicit risk horizons', () => { + it('keeps zero day intervals and does not fill later stages', () => { + const s = stages('2026-01-01', '2026-01-01', '2026-02-01'); + expect(daysBetween(s[0].date, s[1].date)).toBe(0); + expect(s.slice(2).every((x) => x.date === undefined)).toBe(true); + expect(stages('2026-01-01', '2027-01-01', '2026-02-01')[1].date).toBeUndefined(); + }); + it('distinguishes inferred, structured, pending and ambiguous stages', () => { + const a = stages('2026-01-01', undefined, '2026-02-01', { + colposcopy: { state: 'inferred', date: '2026-01-03' }, + biopsy: { state: 'pending' }, + diagnosis: { state: 'ambiguous' }, + }); + expect(a.map((x) => x.state)).toEqual([ + 'Registrada', + 'Desconocida', + 'Registrada', + 'Pendiente', + 'Ambigua', + ]); + expect(a[2].provenance).toBe('Inferida temporalmente'); + expect( + stages('2026-01-01', undefined, '2026-02-01', { + biopsy: { state: 'structured', date: '2026-01-04' }, + })[3].provenance, + ).toBe('Vínculo estructurado'); + }); + it('says an interval in days, marks an inferred one, and prints a dash for a missing date', () => { + expect(intervalText('2026-01-01', '2026-01-01')).toBe('0 días'); + expect(intervalText('2026-01-01', '2026-01-04', true)).toBe('3 días (inferido)'); + expect(intervalText(undefined, '2026-01-04')).toBe('—'); + expect(intervalText('2026-01-05', '2026-01-04')).toBe('—'); + }); + it('uses only a published horizon and preserves zero', () => { + const r: RiskAssessment = { + resourceType: 'RiskAssessment', + status: 'final', + subject: {}, + prediction: [ + { probabilityDecimal: 0, whenRange: { high: { value: 0, code: 'a' } } }, + { probabilityDecimal: 0.2, whenRange: { high: { value: 3, code: 'a' } } }, + ], + }; + expect(horizonRisk(r, 0)?.value).toBe(0); + expect(horizonRisk(r, 5)).toBeUndefined(); + expect(horizonRisk({ ...r, prediction: [] }, 0)).toBeUndefined(); + }); +}); diff --git a/src/app/paciente/stages.html b/src/app/paciente/stages.html new file mode 100644 index 0000000..b6cd699 --- /dev/null +++ b/src/app/paciente/stages.html @@ -0,0 +1,23 @@ +
+ @for (s of rows(); track s.label) { +
+ + @if (detail()) { +
+ {{ s.label }} + {{ s.state }}{{ s.provenance ? ' · ' + s.provenance : '' }} + {{ s.date ?? 'Sin fecha' }} + Desde anterior: {{ s.sincePrevious }} + Desde toma: {{ sinceSample(s) }} +
+ } +
+ } +
diff --git a/src/app/paciente/stages.scss b/src/app/paciente/stages.scss new file mode 100644 index 0000000..b0eee49 --- /dev/null +++ b/src/app/paciente/stages.scss @@ -0,0 +1,116 @@ +:host { + display: block; + min-width: 150px; +} +.stage-line { + display: flex; + align-items: flex-start; +} +.stage { + position: relative; + flex: 0 0 37px; +} +.stage:not(:last-child)::after { + content: ''; + position: absolute; + top: 9px; + left: 20px; + right: 0; + border-top: 1px solid #667b8a; +} +.stage:last-child { + flex-basis: 18px; +} +.node { + display: block; + width: 18px; + height: 18px; + box-sizing: border-box; + border: 2px dashed #667b8a; + border-radius: 50%; + background: white; + position: relative; + z-index: 1; +} +.registered { + background: #387b66; + border-style: solid; +} +.inferred { + background: #4269a0; + border-style: double; +} +.pending { + background: #fff1c9; + border-style: solid; +} +.ambiguous { + border-style: double; + border-color: #a84460; +} + +/* The detailed panel: one column per milestone, across the whole width. */ +.detailed { + background: #fff; + border: 1px solid #dce3e7; + border-radius: 8px; + padding: 18px 12px; +} +.detailed .stage, +.detailed .stage:last-child { + flex: 1; + min-width: 0; + text-align: center; +} +.detailed .node { + margin: 0 auto; +} +.detailed .stage:not(:last-child)::after { + left: calc(50% + 9px); + right: calc(-50% + 9px); +} +.stage-detail { + display: flex; + flex-direction: column; + gap: 3px; + padding: 8px 4px 0; + font-size: 12px; + color: #60717d; + overflow-wrap: anywhere; +} +.stage-detail strong { + color: #243d4b; +} +.interval { + font-weight: 600; + color: #365b69; +} + +@media (max-width: 700px) { + .node { + flex: none; + } + .detailed { + display: block; + } + .detailed .stage { + display: flex; + gap: 12px; + padding-bottom: 10px; + text-align: left; + } + .detailed .stage::after { + top: 18px; + left: 9px; + bottom: 0; + right: auto; + border-top: 0; + border-left: 1px solid #667b8a; + } + .detailed .node { + margin: 0; + } + .stage-detail { + padding: 0; + } +} diff --git a/src/app/paciente/stages.ts b/src/app/paciente/stages.ts new file mode 100644 index 0000000..9671a43 --- /dev/null +++ b/src/app/paciente/stages.ts @@ -0,0 +1,127 @@ +import { Component, computed, input } from '@angular/core'; +import type { DiagnosticReport } from 'fhir/r4'; +import { ext } from '../fhir'; + +export type StageFact = { state?: string; date?: string }; +export type StageFacts = Record; +export function routeFacts(report?: DiagnosticReport): StageFacts { + return Object.fromEntries( + ['colposcopy', 'biopsy', 'diagnosis'].map((k) => [ + k, + { + state: ext(report, `stage-${k}-state`)?.valueCode, + date: ext(report, `stage-${k}-date`)?.valueDate, + }, + ]), + ); +} +export function stages(sample?: string, report?: string, cutoff?: string, facts: StageFacts = {}) { + const valid = (d?: string) => !!d && !!cutoff && /^\d{4}-\d{2}-\d{2}$/.test(d) && d <= cutoff; + const start = valid(sample) ? sample : undefined; + const result = start && valid(report) && report! >= start ? report : undefined; + const later = (label: string, key: string) => { + const f = facts[key]; + const state = + f?.state === 'pending' + ? 'Pendiente' + : f?.state === 'ambiguous' + ? 'Ambigua' + : (f?.state === 'inferred' || f?.state === 'structured') && + valid(f.date) && + start && + f.date! >= start + ? 'Registrada' + : 'Desconocida'; + return { + label, + date: state === 'Registrada' ? f.date : undefined, + state, + provenance: + state === 'Registrada' + ? f.state === 'inferred' + ? 'Inferida temporalmente' + : 'Vínculo estructurado' + : undefined, + }; + }; + return [ + { + label: 'Toma de muestra', + date: start, + state: start ? 'Registrada' : 'Desconocida', + provenance: undefined, + }, + { + label: 'Resultado de citología', + date: result, + state: result ? 'Registrada' : 'Desconocida', + provenance: undefined, + }, + later('Colposcopia', 'colposcopy'), + later('Reporte de biopsia', 'biopsy'), + later('Diagnóstico', 'diagnosis'), + ]; +} +export function daysBetween(a?: string, b?: string): number | undefined { + if (!a || !b) return undefined; + const x = Date.parse(a + 'T00:00:00Z'), + y = Date.parse(b + 'T00:00:00Z'); + return Number.isFinite(x) && Number.isFinite(y) && y >= x ? (y - x) / 86400000 : undefined; +} +/** One stage as the screens say it, with the intervals the detailed panel prints. */ +export interface StageRow { + label: string; + state: string; + provenance?: string; + date?: string; + inferred: boolean; + title: string; + /** "3 días", "3 días (inferido)" or "—": never a zero for a missing date */ + sincePrevious: string; +} + +/** Days between two stages as text; an interval that rests on an inferred stage says so. */ +export function intervalText(from?: string, to?: string, inferred = false): string { + const days = daysBetween(from, to); + return days === undefined ? '—' : `${days} días${inferred ? ' (inferido)' : ''}`; +} + +@Component({ + selector: 'app-stages', + templateUrl: './stages.html', + styleUrl: './stages.scss', +}) +export class Stages { + /** the cytology's sample day, its report day, and the day the route is known by */ + readonly sample = input(); + readonly report = input(); + readonly cutoff = input(); + /** the detailed panel (milestones, states, dates, intervals) instead of the compact line */ + readonly detail = input(false); + readonly facts = input({}); + protected readonly items = computed(() => + stages(this.sample(), this.report(), this.cutoff(), this.facts()), + ); + protected readonly rows = computed(() => { + const items = this.items(); + const inferred = (x?: { provenance?: string }) => x?.provenance === 'Inferida temporalmente'; + return items.map((s, i) => ({ + ...s, + inferred: inferred(s), + title: `${s.label}: ${s.state}${s.provenance ? ' · ' + s.provenance : ''}`, + sincePrevious: intervalText( + i ? items[i - 1].date : undefined, + s.date, + inferred(s) || (i > 0 && inferred(items[i - 1])), + ), + })); + }); + protected readonly summary = computed(() => + this.rows() + .map((r) => r.title) + .join('; '), + ); + protected sinceSample(row: StageRow): string { + return intervalText(this.items()[0].date, row.date, row.inferred); + } +}