One shell with the current look: indicators, follow-up list and patient view from FHIR; /conectar canvas; /revision; Playwright page tests

This commit is contained in:
Roberto Treviño
2026-11-25 10:21:30 -06:00
parent 70b6d6c646
commit cd7bbaf11a
70 changed files with 5459 additions and 182 deletions
+280
View File
@@ -0,0 +1,280 @@
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 {
populations: Record<string, number>;
score?: number;
low?: number;
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
}
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'] = {};
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)]),
);
}
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,
};
}
/** Codes as the screens name them. */
const LABELS: Record<string, string> = {
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',
};
export const STRATA: Record<string, string> = {
category: 'Categoría',
age_group: 'Grupo de edad',
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
};
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<extra></extra>',
},
],
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' } } },
};
}