diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 6e54e0a..6f81469 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -19,19 +19,21 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie r.url().includes('measure=cacu-eu7') && !r.url().includes('%2C'), ); + const catalog = page.waitForResponse((r) => r.url().endsWith('/cacu/fhir/Measure')); await page.goto('/indicadores/cacu'); + const measures = await (await catalog).json(); const eu7 = await (await report).json(); const count = eu7.entry[0].resource.group[0].population.find( (p: any) => p.code.coding[0].code === 'initial-population', ).count; - await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(String(count)); + await expect(page.locator('[data-measure="CACU_EU7"] mat-card-subtitle')).toContainText(String(count)); await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible(); await page.getByRole('tab', { name: 'Trazabilidad' }).click(); - await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14); + await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(measures.total); await page.getByRole('tab', { name: 'Datos y definiciones' }).click(); - await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14); + await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(measures.total); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?')); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); diff --git a/src/app/indicadores/cacu-results.spec.ts b/src/app/indicadores/cacu-results.spec.ts new file mode 100644 index 0000000..9dc7eb1 --- /dev/null +++ b/src/app/indicadores/cacu-results.spec.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; +import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results'; +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('reportes clínicos', () => { + it('counts HPV reports and retains inconsistent and zero categories', () => { + const d = hpvDistribution(report(4, { negative: 2, positive_16: 1, inconsistent: 1 }))!; + 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('excludes missing or unclassifiable histology from the denominator', () => { + const d = biopsyDistribution(report(5, { normal: 1, HSIL: 2, no_data: 1, unclassified: 1 }))!; + expect(d.total).toBe(3); + expect(d.noData).toBe(1); + expect(d.outside).toBe(2); + }); + it('does not fabricate a report or accept mismatched counts', () => { + expect(hpvDistribution(undefined)).toBeUndefined(); + expect(biopsyDistribution(report(2, { normal: 1 }))).toBeUndefined(); + expect(hpvDistribution(report(0, {}))?.total).toBe(0); + }); +}); + +describe('citología EU7', () => { + it('uses eligible results as denominator and preserves outside counts and zero categories', () => { + const result = cytologyDistribution(report(10, { NILM: 6, HSIL: 2, no_data: 2 }))!; + expect(result.total).toBe(8); + expect(result.outside).toBe(2); + expect(result.rows.map((r) => r.count)).toEqual([6, 0, 0, 0, 2, 0]); + }); + it('supports an empty population without inventing percentages', () => { + expect(cytologyDistribution(report(0, {}))).toMatchObject({ total: 0, max: 0, outside: 0 }); + }); + it('rejects absent or inconsistent distributions', () => { + expect(cytologyDistribution(undefined)).toBeUndefined(); + expect(cytologyDistribution(report(3, { NILM: 2 }))).toBeUndefined(); + }); +}); diff --git a/src/app/indicadores/cacu-results.ts b/src/app/indicadores/cacu-results.ts new file mode 100644 index 0000000..b6dfa7b --- /dev/null +++ b/src/app/indicadores/cacu-results.ts @@ -0,0 +1,55 @@ +import { Reading } from './measures'; + +const CATEGORIES = [ + ['NILM', 'Normal', '#408651'], + ['ASC-US', 'ASC-US', '#2778B8'], + ['LSIL', 'LIEBG', '#B19525'], + ['ASC-H', 'ASC-H', '#7955B1'], + ['HSIL', 'LIEAG', '#CE4778'], + ['CIS', 'Carcinoma in situ', '#AA394D'], +] as const; + +/** EU7 selects one sample per patient. Unknown categories stay outside the denominator. */ +export function cytologyDistribution(reading: Reading | undefined) { + return distribution(reading, CATEGORIES); +} + +const HPV = [ + ['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'], +] as const; + +const BIOPSY = [ + ['normal', 'Normal', '#408651'], + ['LSIL', 'LIEBG (CIN 1)', '#B19525'], + ['HSIL', 'LIEAG (CIN 2 y 3)', '#CE4778'], + ['CIS', 'Carcinoma in situ', '#AA394D'], + ['carcinoma', 'Carcinoma invasor', '#8D4C79'], +] as const; + +export function hpvDistribution(reading: Reading | undefined) { + const result = distribution(reading, HPV); + return result && { ...result, total: result.total + result.outside }; +} +export const biopsyDistribution = (reading: Reading | undefined) => distribution(reading, BIOPSY); + +function distribution(reading: Reading | undefined, categories: readonly (readonly [string, string, string])[]) { + 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]) => ({ + label, color, count: cells[code]?.['initial-population'] ?? 0, + })); + const total = rows.reduce((sum, row) => sum + row.count, 0); + const max = Math.max(0, ...rows.map((row) => row.count)); + return { rows, total, outside: population - total, max, + noData: cells['no_data']?.['initial-population'] ?? 0 }; +} diff --git a/src/app/indicadores/measures.ts b/src/app/indicadores/measures.ts index 3c87e87..de0c2e1 100644 --- a/src/app/indicadores/measures.ts +++ b/src/app/indicadores/measures.ts @@ -44,12 +44,14 @@ export function periodTypes(measure: Measure): PeriodType[] { /** What one report says: its counts, its score and interval, and its strata. */ export interface Reading { + error?: boolean; populations: Record; score?: number; low?: number; high?: number; unit?: string; strata: Record>>; + stratumScores?: Record>; } function counts(group: { @@ -65,11 +67,13 @@ 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 ?? []) { const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? ''; strata[name] = Object.fromEntries( (s.stratum ?? []).map((x) => [x.value?.text ?? '', 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')?.valueDecimal, high: ext(x.measureScore, 'q3')?.valueDecimal}])); } return { populations: counts(group), @@ -78,6 +82,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, unit: score?.unit, strata, + stratumScores, }; } @@ -116,6 +121,13 @@ 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', ...Object.fromEntries( ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ), @@ -128,7 +140,18 @@ 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', + 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', }; +/** Measures whose server title says "referral": the data record procedures, not issued referrals. */ +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.' }, +}; +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 { diff --git a/src/app/indicadores/ppv-labels.spec.ts b/src/app/indicadores/ppv-labels.spec.ts new file mode 100644 index 0000000..90eb55d --- /dev/null +++ b/src/app/indicadores/ppv-labels.spec.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { PPV_NOTES, STRATA, measureTitle, name } from './measures'; + +describe('referral PPV wording', () => { + it('never presents procedures or date associations as confirmed referrals', () => { + for (const measure of ['CACU_VPP_COLPOSCOPIA', 'CACU_VPP_BIOPSIA']) { + const { title, note } = PPV_NOTES[measure]; + expect(title).toContain('registrada'); + expect(title.toLowerCase()).not.toContain('referencia'); + expect(note).toContain('asociación por fechas'); + expect(note).toContain('no un vínculo clínico confirmado'); + expect(measureTitle({ name: measure, title: 'VPP de la referencia' })).toBe(title); + } + expect(PPV_NOTES['CACU_VPP_COLPOSCOPIA'].note).toContain('inferirse de notas'); + }); + + it('keeps the server title for other measures', () => { + expect(measureTitle({ name: 'CACU_EU7', title: 'Pacientes evaluadas' })).toBe('Pacientes evaluadas'); + }); + + it('names the new strata and their values in Spanish', () => { + for (const code of ['referral_cytology', 'histology_level', 'screening_round', 'result_initial', 'result_subsequent']) + expect(STRATA[code]).toBeTruthy(); + expect(name('ASCUS+')).toBe('Citología ASC-US o mayor'); + expect(name('LSIL+')).toBe('Citología LIEBG o mayor'); + expect(name('HSIL+')).toBe('Citología LIEAG o mayor'); + expect(name('LIEBG+')).toBe('Histología LIEBG o mayor'); + expect(name('LIEAG+')).toBe('Histología LIEAG o mayor'); + expect(name('invasive')).toBe('Carcinoma invasor'); + expect(name('initial')).toBe('Tamizaje inicial'); + expect(name('subsequent')).toBe('Tamizaje subsecuente'); + }); +}); diff --git a/src/app/indicadores/tab-indicadores.html b/src/app/indicadores/tab-indicadores.html index f0aea1f..737d4df 100644 --- a/src/app/indicadores/tab-indicadores.html +++ b/src/app/indicadores/tab-indicadores.html @@ -52,7 +52,7 @@ @if (layout().route.length) { - Ruta del tamizaje + {{ domain() === 'cacu' ? 'Tiempos de la ruta del tamizaje' : 'Ruta del tamizaje' }} Acumulado desde la toma Por pasos + @if (domain() === 'cacu') { Desglose por CIE-10 } - + @if (domain() !== 'cacu') { } + @else if (routeView() === 'icd10') { +

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

+ @if (reports.isLoading()) {

Calculando…

} + @else if (icd(); as r) { +

{{ r.populations['measure-observation'] ?? 0 }} observaciones · escala 0 a {{ icdMax() }} días.

+ + @for (row of icdRows(); track row.label) { + + } @empty { } +
CIE-10 y descripciónMedianaObservacionesQ1–Q3
{{ row.label }}{{ row.median }} días{{ row.count }}{{ row.low }}–{{ row.high }}
Sin observaciones en el periodo.
+ } @else {

Desglose no disponible en este servidor o periodo.

} + } @else { + @if (routeView() === 'step') { +

Representación ilustrativa: las barras se desplazan según las medianas publicadas por tramo; no representan la duración acumulada observada de una misma cohorte.

+ +
+ Cuartiles y valores por tramo +

Q1, mediana y Q3 corresponden a las observaciones disponibles de cada tramo. Los tramos sin datos se indican como no disponibles.

+ + + @for (row of routeRows(); track row.label) { + + + + } +
TramoMedianaObservacionesQ1–Q3
{{ row.label }}{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}{{ row.reading?.score !== undefined ? (row.reading?.populations?.['measure-observation'] ?? '—') : '—' }}{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}
+
+ } @else { +

Escala: 0 a {{ routeMax() }} días. Las marcas indican el primer y tercer cuartil.

+ + + + @for (row of routeRows(); track row.label) { + + + + } + +
EtapaMedianaObservacionesQ1–Q3
{{ row.label }} + @if (row.reading?.score !== undefined) { + + } + {{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}{{ row.reading?.populations?.['measure-observation'] ?? '—' }}{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}
+ } + }
}

Indicadores clínicos

+@if (domain() === 'cacu') { + + Resultados de citología, VPH y biopsia + +
+

Distribución de resultados citológicos

+ @if (reports.isLoading()) { +

Calculando…

+ } @else if (cytology(); as distribution) { +

{{ distribution.total }} pacientes con resultado elegible · {{ distribution.outside }} fuera de la distribución

+

Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.

+

Escala de las barras: 0 a {{ distribution.max }} pacientes.

+ + + + @for (row of distribution.rows; track row.label) { + + + + + + } + +
CategoríaPacientes%
{{ row.label }}{{ row.count }}{{ distribution.total ? (100 * row.count / distribution.total).toFixed(1) + ' %' : '—' }}
+ @if (!distribution.total) {

Sin resultados elegibles en el periodo.

} + } @else { +

{{ hasCytologyMeasure() ? 'Distribución no disponible para este periodo.' : 'Medida no publicada por el servidor.' }}

+ } +
+
+

Resultados de VPH por genotipo

+ @if (reports.isLoading()) {

Calculando…

} + @else if (hpv(); as d) { +

{{ d.total }} reportes VPH elegibles · periodo por fecha de toma. {{ d.outside }} fuera de las categorías mostradas.

+

Escala de las barras: 0 a {{ d.max }} reportes. El contrato actual no representa resultados indeterminados.

+ + + + @for (row of d.rows; track row.label) { + @if (row.label === 'No clasificable o inconsistente') { } + + + } + +
CategoríaReportes%
IndeterminadoNo disponible en el contrato actual
{{ row.label }}{{ row.count }}{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}
+ @if (!d.total) {

Sin reportes elegibles en el periodo.

} + } @else {

{{ hasHpvMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución no publicada por el servidor.' }}

} +
+
+

Resultado de la biopsia

+ @if (reports.isLoading()) {

Calculando…

} + @else if (biopsy(); as d) { +

{{ d.total }} reportes con histología clasificable · periodo por fecha de reporte.

+

{{ d.noData }} reportes sin grado · {{ d.outside - d.noData }} con grado no clasificable. Las órdenes sin reporte no están incluidas.

+

Escala de las barras: 0 a {{ d.max }} reportes.

+ + + + @for (row of d.rows; track row.label; let i = $index) { + @if (i === 0) { } + @if (i === 2) { } + + + } + +
CategoríaReportes%
Menor que LIEAG · {{ d.rows[0].count + d.rows[1].count }}
LIEAG o más · {{ d.rows[2].count + d.rows[3].count + d.rows[4].count }}
{{ row.label }}{{ row.count }}{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}
+ @if (!d.total) {

Sin reportes con grado clasificable en el periodo.

} + } @else {

{{ hasBiopsyMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución general no publicada por el servidor.' }}

} +
+
+
+
+ Tasa de confirmación histopatológica de referencia a colposcopia +

No disponible: no se identifican las referencias emitidas a colposcopia. Las colposcopias inferidas no acreditan ese denominador.

+
+ Tasa de confirmación histopatológica de referencia a biopsia + +

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.

+ @if (reports.isLoading()) {

Calculando…

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

No disponible: medida no publicada por el servidor.

} + @else if (requests()?.error) {

Error al consultar las solicitudes de biopsia.

} + @else if (requests(); as r) { + @if (validRequests()) { + @if (r.populations['initial-population']; as total) { +

Denominador: {{ total }} solicitudes registradas (no pacientes).

+

LIEAG o más: {{ category(r, 'high_grade') }} / {{ total }} · {{ (100 * category(r, 'high_grade') / total).toFixed(1) }} %

+

Menor que LIEAG: {{ category(r, 'below_high_grade') }} / {{ total }} · {{ (100 * category(r, 'below_high_grade') / total).toFixed(1) }} %

+

Pendientes: {{ category(r, 'pending') }} · Sin grado: {{ category(r, 'no_grade') }} · No clasificables: {{ category(r, 'unclassified') }} · Fechas inconsistentes: {{ category(r, 'inconsistent') }} · Registros fusionados ambiguos: {{ category(r, 'ambiguous') }}.

+ } @else {

Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).

} + } @else {

Los datos de solicitudes recibidos están incompletos o son inconsistentes.

} + } @else {

No disponible para este periodo.

} +
+
+
+}
@for (m of clinical(); track m.id) { - {{ m.title }} + {{ measureTitle(m) }} {{ score(m) }} · {{ detail(m) }} + @if (ppvNote(m); as note) { {{ note }} } + @if (domain() === 'cacu' && m.name === 'CACU_EU7') { El tamizaje inicial o subsecuente es el que declara el formulario o se deduce de la ruta; «Sin dato» si no consta. } + @if (domain() === 'cacu' && m.name === 'CACU_CONFIRMACION_CITOLOGIA') { Pacientes con citología ASC-H, LIEAG o carcinoma in situ; incluye casos sin biopsia. } @for (f of figureSets().get(m.name!) ?? []; track f.title) { diff --git a/src/app/indicadores/tab-indicadores.scss b/src/app/indicadores/tab-indicadores.scss index cdebd88..3fb07da 100644 --- a/src/app/indicadores/tab-indicadores.scss +++ b/src/app/indicadores/tab-indicadores.scss @@ -78,11 +78,46 @@ h2 { 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-values summary:focus-visible { outline: 2px solid var(--color-action); outline-offset: 2px; } + +.route-table td { font-variant-numeric: tabular-nums; } +.route-table th:first-child { width: 70%; } +.duration-track { position: relative; } +.duration-track .bar { background: #42a77e; } +.quartile { position: absolute; top: -3px; width: 2px; height: 14px; background: #17324d; } +.confirmation-cards { display: grid; grid-template-columns: 1fr; gap: var(--space-4); margin-bottom: var(--space-4); } +.confirmation-cards { align-items: start; } +.confirmation-cards p { margin: var(--space-2) 0; } +@media (min-width: 850px) { .confirmation-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); } } .clinical { display: grid; gap: var(--space-4); grid-template-columns: 1fr; + align-items: start; +} + +.results-card { margin-bottom: var(--space-4); } +.results-grid { display: grid; gap: var(--space-4); grid-template-columns: 1fr; } +.results-grid section { min-width: 0; } +.results-grid h3 { font-size: 1rem; font-weight: 500; margin: var(--space-3) 0; } +.results-grid p { font-size: 13px; margin: var(--space-2) 0; } +.distribution { border-collapse: collapse; width: 100%; font-size: 13px; } +.distribution th { font-weight: 500; text-align: left; } +.distribution td, .distribution thead th:not(:first-child) { text-align: right; white-space: nowrap; padding-left: 12px; } +.distribution tbody th { padding: 5px 0; } +.distribution .group th { background: #edf2f4; padding: 6px 8px; font-weight: 600; } +.bar-track { display: block; height: 8px; background: #eef1f3; margin-top: 3px; } +.bar { display: block; height: 100%; } +.results-grid .distribution tbody th:has(.distribution-label) { display: flex; align-items: center; gap: 10px; } +.results-grid .distribution-label { flex: 0 1 45%; min-width: 0; } +.results-grid .bar-track { flex: 1; min-width: 40px; height: 16px; margin: 0; } +.results-grid .distribution td { padding-left: 8px; } +@media (min-width: 850px) { + .results-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .biopsy { grid-column: 1 / -1; } } @media (min-width: 1304px) { diff --git a/src/app/indicadores/tab-indicadores.ts b/src/app/indicadores/tab-indicadores.ts index 730fc6a..b13842d 100644 --- a/src/app/indicadores/tab-indicadores.ts +++ b/src/app/indicadores/tab-indicadores.ts @@ -8,6 +8,7 @@ import type { Measure, MeasureReport } from 'fhir/r4'; import { Fhir, resources } from '../fhir'; import { Figure, Plot } from '../plot'; import { LAYOUTS } from './layout'; +import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results'; import { detail, donut, @@ -21,6 +22,8 @@ import { Reading, scoring, STRATA, + PPV_NOTES, + measureTitle, strataBars, } from './measures'; @@ -49,7 +52,7 @@ export class TabIndicadores { protected readonly chosen = signal(undefined); /** The period the figures show (set by Aplicar). */ protected readonly applied = signal(undefined); - protected readonly routeView = signal<'sample' | 'step'>('sample'); + protected readonly routeView = signal<'sample' | 'step' | 'icd10'>('sample'); protected readonly layout = computed( () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, @@ -64,6 +67,7 @@ export class TabIndicadores { const placed = new Set([ ...this.layout().kpis, ...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]), + ...(this.domain() === 'cacu' ? ['CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS', 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', 'CACU_TIEMPO_DIAGNOSTICO_CIE10'] : []), ]); return this.measures().filter((m) => !placed.has(m.name!)); }); @@ -94,11 +98,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 { + 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) { + if (params.domain === 'cacu' && m.name === 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION') + return [m.name, { populations: {}, strata: {}, error: true } as Reading] as const; + if (params.domain === 'cacu' && ['CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS', 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION', 'CACU_TIEMPO_DIAGNOSTICO_CIE10'].includes(m.name!)) + return [m.name!, undefined] as const; + throw error; + } }), ); return new Map(found); @@ -141,6 +153,64 @@ export class TabIndicadores { }), ); }); + protected readonly routeRows = computed(() => { + const view = this.routeView(); + return this.layout().route.map((s) => { + const m = this.byName().get(view === 'sample' ? s.fromSample : s.fromStep); + return { label: view === 'sample' ? s.label : s.step, reading: m && this.r(m) }; + }); + }); + protected readonly routeMax = computed(() => Math.max(0, ...this.routeRows().map(({reading}) => + Math.max(reading?.score ?? 0, reading?.high ?? 0)))); + /** Illustrative cascade of the published step medians; missing steps do not advance the offset. */ + protected readonly stepRoute = computed
(() => { + const rows = this.routeRows().filter(row => row.reading?.score !== undefined); + let offset = 0; + const bars = rows.map((row, index) => { + const score = row.reading!.score!; + const base = offset; + offset += score; + return { label: row.label, count: row.reading!.populations['measure-observation'] ?? 0, score, base, + color: index === 0 ? '#C9CDD2' : '#A8C243' }; + }); + const max = Math.max(1, offset); + return { + data: [{ type: 'bar', orientation: 'h', y: bars.map(row => `${row.label}
n = ${row.count}`), + x: bars.map(row => row.score), base: bars.map(row => row.base), + marker: { color: bars.map(row => row.color) }, text: bars.map(row => `+${row.score} d`), + textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, + cliponaxis: false, hovertemplate: '%{y}
Mediana del tramo: %{x} días' }], + layout: { autosize: true, showlegend: false, bargap: 0.48, + height: Math.max(210, bars.length * 76 + 94), margin: { t: 12, l: 8, r: 28, b: 52 }, + xaxis: { title: { text: 'Días' }, range: [0, max * 1.12], nticks: 5, fixedrange: true, zeroline: false }, + yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } }, + }; + }); + protected readonly stepRouteHeight = computed(() => Math.max(210, + this.routeRows().filter(row => row.reading?.score !== undefined).length * 76 + 94)); + protected readonly icd = computed(() => this.reports.value()?.get('CACU_TIEMPO_DIAGNOSTICO_CIE10')); + protected readonly icdRows = computed(() => { + const r = this.icd(); + return Object.entries(r?.stratumScores?.['diagnosis_code'] ?? {}).map(([label, score]) => ({ + label: label.replace('sin_codigo', 'Sin código disponible').replace('ambiguo', 'Diagnóstico ambiguo'), + count: r?.strata['diagnosis_code']?.[label]?.['measure-observation'] ?? 0, ...score, + })); + }); + protected readonly icdMax = computed(() => Math.max(0, ...this.icdRows().map(r => Math.max(r.median, r.high ?? 0)))); + protected readonly requestsMeasure = computed(() => this.byName().has('CACU_BIOPSIA_SOLICITUD_CONFIRMACION')); + protected readonly requests = computed(() => this.reports.value()?.get('CACU_BIOPSIA_SOLICITUD_CONFIRMACION')); + protected readonly validRequests = computed(() => { + const r = this.requests(); + const total = r?.populations['initial-population']; + const cells = r?.strata['category']; + if (!r || r.error || total === undefined || !cells) return false; + const counts = Object.values(cells).map((cell) => cell['initial-population']); + return Number.isInteger(total) && total >= 0 && counts.every((n) => Number.isInteger(n) && n >= 0) + && counts.reduce((sum, n) => sum + n, 0) === total; + }); + protected category(r: Reading, key: string): number { + return r.strata['category']?.[key]?.['initial-population'] ?? 0; + } /** Each clinical card's figures, built once per loaded period. */ protected readonly figureSets = computed( @@ -150,6 +220,15 @@ export class TabIndicadores { ), ); + protected readonly cytology = computed(() => + cytologyDistribution(this.reports.value()?.get('CACU_EU7')), + ); + protected readonly hasCytologyMeasure = computed(() => this.byName().has('CACU_EU7')); + protected readonly hpv = computed(() => hpvDistribution(this.reports.value()?.get('CACU_VPH_GENOTIPO'))); + protected readonly biopsy = computed(() => biopsyDistribution(this.reports.value()?.get('CACU_BIOPSIA_RESULTADOS'))); + protected readonly hasHpvMeasure = computed(() => this.byName().has('CACU_VPH_GENOTIPO')); + protected readonly hasBiopsyMeasure = computed(() => this.byName().has('CACU_BIOPSIA_RESULTADOS')); + /** A clinical card's figures: the overall split, then one per stratum. */ private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] { if (!r || !(r.populations['initial-population'] ?? 0)) return []; @@ -160,7 +239,9 @@ export class TabIndicadores { if (kind === 'continuous-variable') return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }]; return [ - { title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) }, + ...(this.domain() === 'cacu' && m.name === 'CACU_EU7' && this.cytology() + ? [] + : [{ title: kind === 'proportion' ? 'Numerador y resto' : 'Por categoría', figure: donut(m, r) }]), ...strata.map((s) => ({ title: `Por ${STRATA[s]?.toLowerCase() ?? s}`, figure: strataBars(m, r, s), @@ -168,4 +249,8 @@ export class TabIndicadores { ]; } protected readonly name = name; + protected readonly measureTitle = measureTitle; + protected ppvNote(m: Measure): string | undefined { + return PPV_NOTES[m.name ?? '']?.note; + } }