import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4'; import { code, ext } from '../fhir'; import { Figure, PALETTE } from '../plot'; export type PeriodType = 'semester' | 'month'; export type Scoring = 'proportion' | 'continuous-variable' | 'cohort'; /** The periods back from today, most recent first: semesters (`2025-S1`) or months. */ export function periods(type: PeriodType, years = 6, today = new Date()): string[] { const found: string[] = []; const year = today.getFullYear(); if (type === 'semester') { for (let y = year; y > year - years; y--) { if (y < year || today.getMonth() >= 6) found.push(`${y}-S2`); found.push(`${y}-S1`); } } else { for (let i = 0; i < years * 12; i++) { const d = new Date(year, today.getMonth() - i, 1); found.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`); } } return found; } export function periodLabel(period: string): string { const [year, part] = period.split('-'); if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`; const month = new Date(Number(year), Number(part) - 1, 1).toLocaleString('es-MX', { month: 'short', }); return `${month} ${year}`; } export function scoring(measure: Measure): Scoring { return code(measure.scoring) as Scoring; } export function periodTypes(measure: Measure): PeriodType[] { return (measure.extension ?? []) .filter((e) => e.url.endsWith('/period-type')) .map((e) => e.valueCode as 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: { population?: { code?: { coding?: { code?: string }[] }; count?: number }[]; }) { return Object.fromEntries( (group.population ?? []).map((p) => [p.code?.coding?.[0]?.code ?? '', p.count ?? 0]), ); } export function reading(report: MeasureReport | undefined): Reading | undefined { const group: MeasureReportGroup | undefined = report?.group?.[0]; 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), score: score?.value, low: (ext(score, 'ic-bajo') ?? ext(score, 'q1'))?.valueDecimal, high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, unit: score?.unit, strata, stratumScores, }; } /** Codes as the screens name them. */ const LABELS: Record = { NILM: 'Normal (NILM)', LSIL: 'LIEBG', HSIL: 'LIEAG', normal: 'Normal', carcinoma: 'Carcinoma', no_data: 'Sin dato', no_biopsy: 'Sin biopsia', pre_colposcopy: 'Pre colposcopia', post_colposcopy: 'Post colposcopia', post_treatment: 'Post tratamiento', case: 'Caso (cáncer)', low: 'Bajo', intermediate: 'Intermedio', high: 'Alto', satisfactory: 'satisfactoria', unsatisfactory: 'insatisfactoria', benign: 'Benigno', in_situ: 'Carcinoma in situ', invasive: 'Carcinoma invasor', cancer: 'Diagnóstico confirmado', pending_biopsy: 'Pendiente de biopsia', biopsy_no_result: 'Biopsia sin resultado', benign_biopsy: 'Biopsia benigna', confirmed: 'Diagnóstico confirmado', in_process: 'En proceso', not_confirmed: 'Sin TEA', mchat_only: 'Solo M-CHAT', psychology: 'Psicología (ADOS-2)', neuropediatrics: 'Neuropediatría', eeg: 'EEG', 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}`]), ), }; /** A follow-up priority's label. */ export const PRIORITY: Record = { high: 'Alta', medium: 'Media', low: 'Baja' }; export const STRATA: Record = { category: 'Categoría', age_group: 'Grupo de edad', 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 { if (!r || r.score === undefined) return 'Sin dato'; switch (scoring(measure)) { case 'proportion': return `${(r.score * 100).toFixed(1)} %`; case 'continuous-variable': return `${Math.round(r.score * 10) / 10} días`; default: return `${r.score}`; } } export function detail(measure: Measure, r: Reading | undefined): string { if (!r) return ''; const p = r.populations; switch (scoring(measure)) { case 'proportion': return r.score === undefined ? 'Sin pacientes en el periodo.' : `${p['numerator']} de ${p['denominator']} pacientes. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`; case 'continuous-variable': return r.score === undefined ? `${p['initial-population'] ?? 0} sin medición en el periodo.` : `Mediana de ${p['measure-observation']} mediciones; cuartiles ${r.low}–${r.high} días.`; default: return `${p['initial-population'] ?? 0} pacientes.`; } } const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`); /** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */ export function donut(measure: Measure, r: Reading, stratifier = 'category'): Figure { let labels: string[], values: number[]; if (scoring(measure) === 'proportion') { const { numerator = 0, denominator = 0 } = r.populations; labels = ['Numerador', 'Resto']; values = [numerator, denominator - numerator]; } else { const cells = Object.entries(r.strata[stratifier] ?? {}); labels = cells.map(([v]) => name(v)); values = cells.map(([, c]) => c['initial-population'] ?? 0); } return { data: [ { type: 'pie', hole: 0.62, labels, values, sort: false, textinfo: 'value+percent', marker: { colors: PALETTE }, }, ], layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } }, }; } /** Bars per stratum: the rate (proportion) or the count (others). */ export function strataBars(measure: Measure, r: Reading, stratifier: string): Figure { const cells = Object.entries(r.strata[stratifier] ?? {}); const proportion = scoring(measure) === 'proportion'; const values = cells.map(([, c]) => proportion ? c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0 : (c['initial-population'] ?? 0), ); return { data: [ { type: 'bar', orientation: 'h', y: cells.map(([v]) => name(v)), x: values, marker: { color: PALETTE[0] }, }, ], layout: { xaxis: { title: { text: proportion ? '%' : 'Pacientes' } }, yaxis: { automargin: true }, margin: { t: 8, r: 16, b: 48, l: 8 }, }, }; } /** Horizontal median bars with their interquartile range, one per measure. */ export function medians(rows: { label: string; r: Reading | undefined }[]): Figure { const shown = rows.filter((x) => x.r?.score !== undefined); return { data: [ { type: 'bar', orientation: 'h', y: shown.map((x) => x.label), x: shown.map((x) => x.r!.score!), error_x: { type: 'data', symmetric: false, array: shown.map((x) => (x.r!.high ?? x.r!.score!) - x.r!.score!), arrayminus: shown.map((x) => x.r!.score! - (x.r!.low ?? x.r!.score!)), color: '#17324d', }, marker: { color: PALETTE[0] }, hovertemplate: '%{y}: %{x} días', }, ], layout: { xaxis: { title: { text: 'Días (mediana, Q1–Q3)' } }, yaxis: { automargin: true, autorange: 'reversed' }, }, }; } /** A measure over time: % with its interval, median with its quartiles, or counts by category. */ export function history( measure: Measure, series: { period: string; r: Reading | undefined }[], ): Figure { const x = series.map((s) => periodLabel(s.period)); const kind = scoring(measure); if (kind === 'cohort') { const categories = [ ...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {}))), ]; return { data: categories.map((c, i) => ({ type: 'bar', name: name(c), x, y: series.map((s) => s.r?.strata['category']?.[c]?.['initial-population'] ?? 0), marker: { color: PALETTE[i % PALETTE.length] }, })), layout: { barmode: 'stack', yaxis: { title: { text: 'Pacientes' } } }, }; } const k = kind === 'proportion' ? 100 : 1; const value = (v?: number) => (v === undefined ? null : v * k); return { data: [ { x, y: series.map((s) => value(s.r?.high)), mode: 'lines', line: { width: 0 }, showlegend: false, hoverinfo: 'skip', }, { x, y: series.map((s) => value(s.r?.low)), mode: 'lines', line: { width: 0 }, fill: 'tonexty', fillcolor: 'rgba(168,194,67,0.25)', name: kind === 'proportion' ? 'IC 95 %' : 'Q1–Q3', }, { x, y: series.map((s) => value(s.r?.score)), mode: 'lines+markers', name: kind === 'proportion' ? '%' : 'Mediana', line: { color: PALETTE[0] }, }, ], layout: { yaxis: { title: { text: kind === 'proportion' ? '%' : 'Días' } } }, }; }