ISSSTELEON 2fe5301

This commit is contained in:
Roberto Treviño
2026-12-01 09:59:57 -06:00
parent 157006954c
commit c1c81449a9
23 changed files with 1668 additions and 209 deletions
+184
View File
@@ -0,0 +1,184 @@
import { CIE10 } from './cie10';
import { name, Reading } from './measures';
export type Category = {
code: string;
label: string;
color: string;
};
export type Mode = {
label: string;
caption?: string;
} & (
| {
kind: 'counts';
measure: string;
catalog: Category[];
}
| {
kind: 'shares';
measure: string;
stratum: string;
order: string[];
}
| {
kind: 'positives';
measure: string;
stratum: string;
order: string[];
}
| {
kind: 'signs';
measure: string;
strata: string[];
}
| {
kind: 'days';
steps: {
label: string;
measure: string;
}[];
}
| {
kind: 'days-by';
measure: string;
stratum: string;
}
| {
kind: 'figure';
measure: string;
figure: 'donut' | 'scenarios';
catalog?: Category[];
}
);
export interface Bar {
label: string;
color?: string;
width: number;
marks: number[];
cells: string[];
}
export interface Bars {
head: string[];
rows: Bar[];
}
const pct = (n: number, of: number) => (of ? `${((100 * n) / of).toFixed(1)} %` : '—');
const size = (cell?: Record<string, number>) => cell?.['initial-population'] ?? 0;
const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) {
case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
if (!total) return undefined;
const named = mode.catalog.map((c) => c.code);
const rest = Object.keys(cells).filter((c) => !named.includes(c));
const all = [
...mode.catalog,
...rest.map((code) => ({ code, label: name(code), color: '#9AA3AB' })),
];
const most = Math.max(...Object.values(cells).map(size));
return {
head: ['n', '%'],
rows: all.map(({ code, label, color }) => {
const n = size(cells[code]);
const cols = [`${n}`, pct(n, total)];
return { label, color, width: (100 * n) / most, marks: [], cells: cols };
}),
};
}
case 'shares': {
const cells = of(mode.measure)?.strata[mode.stratum] ?? {};
return ratios(
mode.order
.filter((c) => cells[c])
.map((c) => [name(c), cells[c]['numerator'] ?? 0, cells[c]['denominator'] ?? 0]),
);
}
case 'positives': {
const cells = of(mode.measure)?.strata[`${mode.stratum}-category`] ?? {};
const found = new Set(Object.keys(cells).map((k) => k.split('|')[0]));
return ratios(
mode.order
.filter((c) => found.has(c))
.map((c) => {
const positive = size(cells[`${c}|positive`]);
return [name(c), positive, positive + size(cells[`${c}|negative`])];
}),
);
}
case 'signs': {
const strata = of(mode.measure)?.strata ?? {};
return ratios(
mode.strata
.filter((s) => Object.keys(strata[s] ?? {}).length)
.map((s) => {
const positive = size(strata[s]['positive']);
return [name(s), positive, positive + size(strata[s]['negative'])];
}),
);
}
case 'days':
return medians(
mode.steps.map(({ label, measure }) => {
const r = of(measure);
return { label, n: r?.populations['measure-observation'] ?? 0, score: r };
}),
);
case 'days-by': {
const r = of(mode.measure);
const cells = r?.strata[mode.stratum] ?? {};
return medians(
Object.keys(cells)
.map((c) => ({
label: CIE10[c] ? `${c} · ${CIE10[c]}` : name(c),
n: cells[c]['measure-observation'] ?? 0,
score: r?.scores?.[mode.stratum]?.[c],
}))
.sort((a, b) => b.n - a.n),
);
}
default:
return undefined;
}
}
function ratios(rows: [string, number, number][]): Bars | undefined {
if (!rows.length) return undefined;
return {
head: ['n/N', '%'],
rows: rows.map(([label, n, total]) => ({
label,
width: total ? (100 * n) / total : 0,
marks: [],
cells: [`${n}/${total}`, pct(n, total)],
})),
};
}
type Score = {
score?: number;
low?: number;
high?: number;
};
function medians(
rows: {
label: string;
n: number;
score?: Score;
}[],
): Bars | undefined {
if (!rows.some((r) => r.score?.score !== undefined)) return undefined;
const top = Math.max(...rows.flatMap((r) => [r.score?.score ?? 0, r.score?.high ?? 0])) || 1;
const at = (v: number) => (100 * v) / top;
return {
head: ['Mediana', 'n', 'Q1–Q3'],
rows: rows.map(({ label, n, score: s }) => {
if (s?.score === undefined) return { label, width: 0, marks: [], cells: ['—', `${n}`, '—'] };
const spread = s.low !== undefined && s.high !== undefined ? [s.low, s.high] : [];
return {
label,
width: at(s.score),
marks: spread.map(at),
cells: [`${days(s.score)} días`, `${n}`, spread.map(days).join('–') || '—'],
};
}),
};
}
+18
View File
@@ -0,0 +1,18 @@
export const CIE10: Record<string, string> = {
Z014: 'Examen ginecológico',
Z124: 'Pesquisa de tumor del cuello uterino',
B977: 'Papilomavirus',
R876: 'Citología cervical anormal',
N870: 'Displasia cervical leve',
N871: 'Displasia cervical moderada',
N872: 'Displasia cervical severa',
N879: 'Displasia cervical no especificada',
D060: 'Carcinoma in situ del endocérvix',
D061: 'Carcinoma in situ del exocérvix',
D067: 'Carcinoma in situ de otras partes del cuello',
D069: 'Carcinoma in situ del cuello',
C530: 'Cáncer del endocérvix',
C531: 'Cáncer del exocérvix',
C538: 'Cáncer de sitios contiguos del cuello',
C539: 'Cáncer del cuello uterino',
};
-35
View File
@@ -9,41 +9,6 @@ function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
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}<br>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}<br>mediana %{x} días<extra></extra>',
} as Partial<Plotly.Data>,
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', zeroline: false },
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
+46
View File
@@ -0,0 +1,46 @@
import type { Sheet } from '../export';
import { STATES } from '../paciente/stages';
import type { Row } from './follow-up';
import { name } from './measures';
const NONE = 'No disponible';
const HEAD = [
'Paciente',
'CURP',
'Edad',
'Estatus',
'Etapas',
'Última citología',
'VPH',
'Biopsia',
'LIEAG+',
'Cáncer',
'Días a diagnóstico',
];
export function cytologyResult(c: NonNullable<Row['cytology']>): string {
if (c.result) return name(c.result);
return c.adequacy === 'unsatisfactory' ? 'Insatisfactoria' : 'Pendiente';
}
const percent = (p?: number) => (p === undefined ? NONE : `${(100 * p).toFixed(1)} %`);
export function followUpSheet(rows: Row[], query: [string, string][]): Sheet {
return {
title: 'Resultados de seguimiento',
query: [...query, ['Registros', `${rows.length}`]],
head: HEAD,
rows: rows.map((r) => [
r.name ?? r.patient.id!.slice(0, 10),
r.curp ?? NONE,
`${r.age ?? NONE}`,
name(r.status),
r.stages
.filter((s) => s.state !== 'unknown')
.map((s) => `${s.label}: ${s.day ?? STATES[s.state]}`)
.join('\n'),
r.cytology ? `${cytologyResult(r.cytology)} (${r.cytology.date})` : NONE,
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'} (${r.hpv.date})` : NONE,
r.biopsy ? `${name(r.biopsy.histology ?? '') || 'Sin grado'} (${r.biopsy.date})` : NONE,
percent(r.risk.cin2),
percent(r.risk.cancer),
`${r.daysToDiagnosis ?? NONE}`,
]),
};
}
+24 -4
View File
@@ -1,11 +1,14 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
import { route, Stage } from '../paciente/stages';
export interface Row {
patient: Patient;
name?: string;
curp?: string;
status: string;
ageGroup: string;
age?: number;
stages: Stage[];
cytology?: {
date: string;
result?: string;
@@ -30,15 +33,30 @@ const AGE_GROUPS: [number, number][] = [
[45, 54],
[55, 64],
];
export function ageAt(birth: string | undefined, at: string): number | undefined {
if (!birth) return undefined;
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
return y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
}
export function bornFor(at: string, from: number | null, to: number | null): string[] {
const back = (years: number) => `${Number(at.slice(0, 4)) - years}${at.slice(4)}`;
return [
...(from === null ? [] : [`le${valid(back(from))}`]),
...(to === null ? [] : [`gt${valid(back(to + 1))}`]),
];
}
const valid = (day: string) =>
day.endsWith('-02-29') && new Date(`${day}T00:00:00Z`).getUTCMonth() !== 1
? `${day.slice(0, 8)}28`
: day;
export function ageGroup(
birth: string | undefined,
at: string,
groups: [number, number][] = AGE_GROUPS,
): string {
if (!birth) return 'Sin dato';
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const age = ageAt(birth, at);
if (age === undefined) return 'Sin dato';
const found = groups.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`;
return age < groups[0][0] ? `<${groups[0][0]}` : `${groups.at(-1)![1] + 1}+`;
@@ -103,6 +121,8 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
age: ageAt(patient.birthDate, cutoff),
stages: route(last, cutoff),
cytology: last && {
date: last.effectiveDateTime!,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
+42
View File
@@ -42,6 +42,17 @@ export interface Reading {
high?: number;
unit?: string;
strata: Record<string, Record<string, Record<string, number>>>;
scores?: Record<
string,
Record<
string,
{
score?: number;
low?: number;
high?: number;
}
>
>;
}
function counts(group: {
population?: {
@@ -62,6 +73,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined;
const score = group.measureScore;
const strata: Reading['strata'] = {};
const scores: NonNullable<Reading['scores']> = {};
for (const s of group.stratifier ?? []) {
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
strata[name] = Object.fromEntries(
@@ -72,6 +84,13 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
counts(x),
]),
);
for (const { value, measureScore: own } of s.stratum ?? [])
if (own)
(scores[name] ??= {})[value?.text ?? ''] = {
score: own.value,
low: ext(own, 'q1')?.valueDecimal,
high: ext(own, 'q3')?.valueDecimal,
};
}
return {
populations: counts(group),
@@ -80,6 +99,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit,
strata,
scores,
};
}
export const LABELS: Record<string, string> = {
@@ -116,6 +136,21 @@ export const LABELS: Record<string, string> = {
good: 'Bueno',
bad: 'Malo',
not_analyzed: 'Sin analizar',
initial: 'Inicial',
subsequent: 'Subsecuente',
positive: 'Positivo',
negative: 'Negativo',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
ascus_plus: 'ASC-US o mayor',
lsil_plus: 'LIEBG o mayor',
hsil_plus: 'LIEAG o mayor',
cin1_plus: 'Histología LIEBG o mayor',
cin2_plus: 'Histología LIEAG o mayor',
several: 'Varios códigos',
no_result: 'Sin resultado de VPH',
inconsistent: 'Inconsistente',
no_grade: 'Sin grado',
...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
),
@@ -127,6 +162,13 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía',
diagnosis_code: 'Diagnóstico CIE-10',
cytology: 'Citología previa',
hpv: 'VPH de la citología previa',
level: 'Histología confirmada',
round: 'Tamizaje inicial o subsecuente',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
};
export const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string {
+270
View File
@@ -0,0 +1,270 @@
import type { Mode } from './bars';
import type { Catalog, Page, ReadingsCard } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
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' },
],
};
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'],
};
const HPV = [
{ code: 'negative', label: 'Negativo', color: '#A8C243' },
{ code: 'positive_16', label: 'VPH 16', color: '#C24269' },
{ code: 'positive_18', label: 'VPH 18', color: '#9C42C2' },
{ code: 'positive_16_18', label: 'VPH 16 y 18', color: '#92324F' },
{ code: 'positive_other', label: 'Otro de alto riesgo', color: '#C54C71' },
{ code: 'positive_incomplete', label: 'Positivo, genotipo incompleto', color: '#C9577A' },
];
const REQUESTS = [
{ code: 'high_grade', label: 'LIEAG o más', color: '#C24269' },
{ code: 'below_high_grade', label: 'Menor que LIEAG', color: '#A8C243' },
{ code: 'pending', label: 'Pendiente', color: '#C9CDD2' },
{ code: 'no_grade', label: 'Sin grado', color: '#9AA3AB' },
];
const ppv = (measure: string, title: string, note: string, ...more: Mode[]): ReadingsCard => ({
kind: 'readings',
title,
headline: measure,
note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut' },
{
kind: 'shares',
label: 'Citología previa',
caption: 'La última válida de los 365 días anteriores; cada grupo incluye los más severos.',
measure,
stratum: 'cytology',
order: ['ascus_plus', 'lsil_plus', 'hsil_plus', 'no_data'],
},
{
kind: 'shares',
label: 'VPH previo',
caption: 'Los grupos se traslapan.',
measure,
stratum: 'hpv',
order: ['negative', 'positive', 'hpv_16', 'hpv_18', 'no_data'],
},
{
kind: 'shares',
label: 'Nivel de histología',
measure,
stratum: 'level',
order: ['cin1_plus', 'cin2_plus', 'carcinoma'],
},
{
kind: 'shares',
label: 'Tamizaje',
measure,
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
...more,
],
});
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
export const CACU: Page = {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
opportunity: [
{
kind: 'readings',
title: 'Tiempos de la ruta del tamizaje',
note: 'Mediana en días; las marcas son el primer y el tercer cuartil.',
modes: [
{
kind: 'days',
label: 'Acumulado desde la toma',
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: 'days',
label: 'Por pasos',
caption: 'Cada paso mide a sus propias pacientes: las medianas no se suman.',
steps: [
{ label: 'Toma a resultado de citología', measure: 'CACU_EU_TIEMPO_REPORTE' },
{ label: 'Resultado a colposcopía', measure: 'CACU_DIAS_RESULTADO_COLPOSCOPIA' },
{ label: 'Colposcopía a biopsia', measure: 'CACU_DIAS_COLPOSCOPIA_BIOPSIA' },
{ label: 'Biopsia a diagnóstico', measure: 'CACU_DIAS_BIOPSIA_DIAGNOSTICO' },
],
},
{
kind: 'days-by',
label: 'Por CIE-10',
caption: 'Días de la toma al diagnóstico, por el código de la nota que lo fecha.',
measure: 'CACU_TIEMPO_DIAGNOSTICO_CIE10',
stratum: 'diagnosis_code',
},
],
},
],
clinical: [
{
kind: 'columns',
title: 'Resultados de citología, VPH y biopsia',
sections: [
{
kind: 'readings',
title: 'Distribución de resultados citológicos',
note: 'Pacientes, por su última muestra válida del periodo.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_EU7',
catalog: CYTOLOGY.categories,
},
{
kind: 'figure',
label: 'Por escenario clínico',
measure: 'CACU_EU7',
figure: 'scenarios',
catalog: CYTOLOGY.categories,
},
],
},
{
kind: 'readings',
title: 'Resultados de VPH por genotipo',
note: 'Reportes, por fecha de toma.',
modes: [{ kind: 'counts', label: 'General', measure: 'CACU_VPH_GENOTIPO', catalog: HPV }],
},
{
kind: 'readings',
title: 'Resultados de biopsia cervical',
note: 'Reportes, por fecha de reporte.',
modes: [
{
kind: 'counts',
label: 'General',
measure: 'CACU_BIOPSIA_RESULTADOS',
catalog: BIOPSY.categories,
},
],
},
],
},
{
kind: 'readings',
title: 'Pacientes evaluadas por resultado de VPH',
headline: 'CACU_VPH',
note: 'Una vez cada paciente, por su última muestra con resultado.',
modes: [
{ kind: 'figure', label: 'Total', measure: 'CACU_VPH', figure: 'donut' },
{
kind: 'positives',
label: 'Por grupo de edad',
measure: 'CACU_VPH',
stratum: 'age_group',
order: ['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'no_data'],
},
{
kind: 'positives',
label: 'Por estatus de seguimiento',
measure: 'CACU_VPH',
stratum: 'follow_up_status',
order: ['pre_colposcopy', 'post_colposcopy', 'post_treatment', 'case'],
},
{
kind: 'signs',
label: 'Por genotipo',
measure: 'CACU_VPH',
strata: ['hpv_16', 'hpv_18'],
},
{
kind: 'positives',
label: 'Por tamizaje',
measure: 'CACU_VPH',
stratum: 'round',
order: ['initial', 'subsequent', 'no_data'],
},
],
},
{
kind: 'choice',
title: 'Tasa de confirmación histopatológica',
choices: [
{
label: 'Colposcopía',
section: ppv(
'CACU_VPP_COLPOSCOPIA',
'Valor predictivo positivo de la colposcopía',
'Pacientes con colposcopía en el periodo; biopsia solicitada en los 60 días siguientes.',
),
},
{
label: 'Biopsia',
section: ppv(
'CACU_VPP_BIOPSIA',
'Valor predictivo positivo de la biopsia',
'Pacientes con biopsia reportada, por fecha de solicitud.',
{
kind: 'counts',
label: 'Solicitudes',
caption: 'Solicitudes de biopsia registradas, según su resultado.',
measure: 'CACU_BIOPSIA_SOLICITUD_CONFIRMACION',
catalog: REQUESTS,
},
),
},
],
},
],
};
+19 -120
View File
@@ -1,3 +1,5 @@
import type { Mode } from './bars';
import { CACU } from './pages-cacu';
export interface Page {
kpis: Kpi[];
opportunity?: Section[];
@@ -10,13 +12,26 @@ export interface Kpi {
value?: string;
note?: string;
}
export interface ReadingsCard {
kind: 'readings';
title: string;
headline?: string;
note?: string;
modes: Mode[];
}
export type Section =
| ReadingsCard
| {
kind: 'route';
kind: 'columns';
title: string;
steps: {
sections: ReadingsCard[];
}
| {
kind: 'choice';
title: string;
choices: {
label: string;
measure: string;
section: ReadingsCard;
}[];
}
| {
@@ -98,38 +113,6 @@ export interface Catalog {
}
const OLIVE = '#A8C243';
const ROSE = '#C24269';
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' },
],
};
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'],
};
const CACU_DAYS = {
value: '{median} días (mediana)',
note: '{obs} citologías; primer cuartil: {q1} días; tercer cuartil: {q3} días.',
};
const CAMA_DAYS = {
value: '{median} días (mediana)',
note: '{obs} mastografías; Q1 a Q3: {q1} a {q3} días.',
@@ -353,91 +336,7 @@ export const PAGES: Record<string, Page> = {
},
],
},
cacu: {
anchor: 'CACU_EU7',
kpis: [
{
measure: 'CACU_EU7',
title: 'Pacientes evaluadas',
value: '{n} pacientes',
note: 'Pacientes con citología tomada en el periodo.',
},
{
measure: 'CACU_EU_TIEMPO_REPORTE',
title: 'Tiempo desde la toma de muestra al resultado',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Tiempo de tamizaje a diagnóstico',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_TOMA_TRATAMIENTO',
title: 'Tiempo de tamizaje a tratamiento',
...CACU_DAYS,
},
{
measure: 'CACU_DIAS_DIAGNOSTICO_TRATAMIENTO',
title: 'Tiempo de diagnóstico a tratamiento',
...CACU_DAYS,
},
],
clinical: [
{
kind: 'route',
title: 'Tiempos de la ruta del tamizaje',
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',
},
{
kind: 'scenario-bars',
title: 'TOTAL por escenario clínico, {p}',
measure: 'CACU_EU7',
catalog: CYTOLOGY,
stratum: 'follow_up_status',
},
],
},
{
kind: 'figures',
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',
},
],
},
],
},
cacu: CACU,
};
export interface HistoryPanel {
title: string;
+140
View File
@@ -0,0 +1,140 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { Loading } from '../loading';
import { Figure, Plot } from '../plot';
import { bars, Mode } from './bars';
import { Reading } from './measures';
@Component({
selector: 'app-readings',
imports: [Loading, MatButtonToggleModule, Plot],
template: `
<h3 class="title">{{ title() }}</h3>
@if (headline()) {
<p class="headline">{{ headline() }}</p>
}
@if (note()) {
<p class="state">{{ note() }}</p>
}
@if (modes().length > 1) {
<mat-button-toggle-group
[attr.aria-label]="title()"
[value]="mode().label"
(change)="chosen.set($event.value)"
>
@for (m of modes(); track m.label) {
<mat-button-toggle [value]="m.label">{{ m.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
}
@if (mode().caption) {
<p class="state">{{ mode().caption }}</p>
}
@if (loading()) {
<app-loading what="la figura" [figure]="true" />
} @else if (figure(); as f) {
<app-plot [figure]="f" [height]="300" />
} @else if (table(); as t) {
<table [attr.aria-label]="mode().label">
<thead>
<tr>
<th></th>
@for (h of t.head; track h) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (row of t.rows; track row.label) {
<tr>
<th scope="row">
{{ row.label }}
<span class="track" aria-hidden="true">
<span
class="bar"
[style.width.%]="row.width"
[style.background]="row.color"
></span>
@for (m of row.marks; track $index) {
<span class="mark" [style.left.%]="m"></span>
}
</span>
</th>
@for (c of row.cells; track $index) {
<td>{{ c }}</td>
}
</tr>
}
</tbody>
</table>
} @else {
<p class="state">Sin datos en el periodo.</p>
}
`,
styles: `
:host {
display: block;
min-width: 0;
}
.title {
margin: 0 0 8px;
}
.headline {
font-weight: 500;
}
mat-button-toggle-group {
flex-wrap: wrap;
margin: 4px 0;
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
font-weight: 400;
padding: 4px 6px;
text-align: right;
white-space: nowrap;
}
th[scope='row'] {
text-align: left;
white-space: normal;
width: 60%;
}
.track {
background: rgba(0, 0, 0, 0.06);
display: block;
height: 8px;
position: relative;
}
.bar {
background: #a8c243;
display: block;
height: 100%;
}
.mark {
background: #333;
height: 12px;
position: absolute;
top: -2px;
width: 2px;
}
`,
})
export class Readings {
readonly title = input.required<string>();
readonly headline = input('');
readonly note = input('');
readonly modes = input.required<Mode[]>();
readonly loading = input(false);
readonly read = input.required<(measure: string) => Reading | undefined>();
readonly draw = input.required<(mode: Mode) => Figure | undefined>();
protected readonly chosen = signal('');
protected readonly mode = computed(
() => this.modes().find((m) => m.label === this.chosen()) ?? this.modes()[0],
);
protected readonly table = computed(() => bars(this.mode(), this.read()));
protected readonly figure = computed(() =>
this.mode().kind === 'figure' ? this.draw()(this.mode()) : undefined,
);
}
+105
View File
@@ -0,0 +1,105 @@
import { Component, computed, input, signal } from '@angular/core';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import type { Measure } from 'fhir/r4';
import { Mode } from './bars';
import { scenarioBars } from './figures';
import { detail, donut, formatScore, name, Reading, scoring } from './measures';
import type { Section } from './pages';
import { Readings } from './readings';
export interface Source {
loading: boolean;
reading: (measure: string) => Reading | undefined;
measure: (name: string) => Measure | undefined;
}
type Shown = Extract<
Section,
{
kind: 'readings' | 'columns' | 'choice';
}
>;
@Component({
selector: 'app-section',
imports: [MatButtonToggleModule, MatCardModule, Readings],
template: `
@let s = section();
@if (s.kind === 'readings') {
<mat-card appearance="outlined">
<mat-card-content>
<app-readings
[title]="s.title"
[headline]="headline()"
[note]="s.note ?? ''"
[modes]="s.modes"
[loading]="of().loading"
[read]="of().reading"
[draw]="draw()"
/>
</mat-card-content>
</mat-card>
} @else {
<h2>{{ s.title }}</h2>
@if (s.kind === 'columns') {
<div class="columns">
@for (inner of s.sections; track $index) {
<app-section [section]="inner" [of]="of()" />
}
</div>
} @else {
@let open = chosen() || s.choices[0].label;
<mat-button-toggle-group
[attr.aria-label]="s.title"
[value]="open"
(change)="chosen.set($event.value)"
>
@for (c of s.choices; track c.label) {
<mat-button-toggle [value]="c.label">{{ c.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@for (c of s.choices; track c.label) {
@if (c.label === open) {
<app-section [section]="c.section" [of]="of()" />
}
}
}
}
`,
styles: `
:host {
display: block;
margin-top: 16px;
min-width: 0;
}
.columns {
display: grid;
column-gap: 16px;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 480px), 1fr));
}
.columns > :last-child:nth-child(odd) {
grid-column: 1 / -1;
}
`,
})
export class ReadingsSection {
readonly section = input.required<Shown>();
readonly of = input.required<Source>();
protected readonly chosen = signal('');
protected readonly headline = computed(() => {
const s = this.section();
const code = s.kind === 'readings' ? s.headline : undefined;
const measure = code && this.of().measure(code);
const r = code && this.of().reading(code);
if (!measure || !r) return '';
const words = detail(measure, r);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
});
protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure);
const measure = this.of().measure(mode.measure);
if (!measure || !r?.populations['initial-population']) return undefined;
if (mode.figure === 'donut') return donut(measure, r);
const categories = (mode.catalog ?? []).map((c) => ({ ...c, group: '' }));
return scenarioBars(r, { groups: [], categories }, 'follow_up_status', name);
});
}
+4 -9
View File
@@ -85,15 +85,10 @@
<ng-template #sectionView let-section let-period="period">
@switch (section.kind) {
@case ('route') {
<h3 class="route-title">{{ section.title }}</h3>
@if (reports.isLoading()) {
<app-loading what="los tiempos de la ruta" [figure]="true" />
} @else if (routeOf(section); as fig) {
<app-plot [figure]="fig" [height]="300" />
} @else {
<p class="state">Sin tiempos publicados en el periodo.</p>
}
@case ('readings')
@case ('columns')
@case ('choice') {
<app-section [section]="section" [of]="of()" />
}
@case ('tea-summary') {
@if (teaSummary(); as t) {
+10 -6
View File
@@ -17,7 +17,6 @@ import {
fill,
nestedDonut,
rateDots,
routeFigure,
scenarioBars,
shareDonut,
} from './figures';
@@ -38,6 +37,7 @@ import {
strataBars,
} from './measures';
import { Loading } from '../loading';
import { ReadingsSection, Source } from './section';
@Component({
selector: 'app-tab-indicadores',
imports: [
@@ -49,6 +49,7 @@ import { Loading } from '../loading';
MatCardModule,
MatSelectModule,
Plot,
ReadingsSection,
],
templateUrl: './tab-indicadores.html',
styleUrl: './tab-indicadores.scss',
@@ -241,11 +242,14 @@ export class TabIndicadores {
protected measureTitle(code: string | undefined): string {
return (code && this.byName().get(code)?.title) || '';
}
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;
}
protected readonly of = computed<Source>(() => {
const found = this.loaded();
return {
loading: this.reports.isLoading(),
reading: (code) => found?.get(code),
measure: (code) => this.byName().get(code),
};
});
protected figureOf(spec: FigureSpec): Figure | undefined {
const r = this.rd(spec.measure);
if (!r || !(r.populations['initial-population'] ?? 0)) return undefined;
+72 -13
View File
@@ -10,6 +10,30 @@
name="cutoff"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad mínima</mat-label>
<input
matInput
type="number"
min="0"
max="120"
[ngModel]="ageFrom()"
(ngModelChange)="setAge(ageFrom, $event)"
name="ageFrom"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Edad máxima</mat-label>
<input
matInput
type="number"
min="0"
max="120"
[ngModel]="ageTo()"
(ngModelChange)="setAge(ageTo, $event)"
name="ageTo"
/>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Ventana de meses</mat-label>
<mat-select [value]="window()" (selectionChange)="window.set($event.value)">
@@ -51,7 +75,26 @@
}
</mat-select>
</mat-form-field>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('xlsx')"
>
Exportar Excel
</button>
<button
mat-stroked-button
type="button"
[disabled]="saving() || !applied()"
(click)="save('pdf')"
>
Exportar PDF
</button>
</form>
@if (saveError()) {
<p class="muted" role="alert">{{ saveError() }}</p>
}
@if (error()) {
<p class="muted" role="alert">
@@ -72,8 +115,9 @@
<thead>
<tr>
<th>Paciente</th>
<th>Grupo de edad</th>
<th>Edad</th>
<th>Estatus de seguimiento</th>
<th>Etapas</th>
<th>Última citología</th>
<th>Último resultado de VPH</th>
<th>Última biopsia</th>
@@ -87,24 +131,34 @@
@for (row of rows(); track row.patient.id) {
<tr>
<td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{
row.name ?? row.patient.id!.slice(0, 10)
}}</a>
<a
[routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]"
[queryParams]="{ corte: applied(), citologia: row.cytology?.date }"
>{{ row.name ?? row.patient.id!.slice(0, 10) }}</a
>
@if (row.curp) {
<div class="muted curp">{{ row.curp }}</div>
}
</td>
<td>{{ row.ageGroup }}</td>
<td>
{{ row.age ?? 'No disponible' }}
<small>Grupo: {{ row.ageGroup }}</small>
</td>
<td>{{ name(row.status) }}</td>
<td>
<app-stages [stages]="row.stages" />
<button
mat-button
type="button"
[attr.aria-expanded]="opened() === row.patient.id"
(click)="toggle(row)"
>
Detalle
</button>
</td>
<td>
@if (row.cytology; as c) {
{{
c.result
? name(c.result)
: c.adequacy === 'unsatisfactory'
? 'Insatisfactoria'
: 'Pendiente'
}}
{{ result(c) }}
<small>Fecha: {{ c.date }}</small>
<small>Calidad: {{ c.adequacy ? name(c.adequacy) : '—' }}</small>
} @else {
@@ -154,10 +208,15 @@
<td>{{ latest(row) ?? 'No disponible' }}</td>
<td class="num">{{ row.daysToDiagnosis ?? 'No disponible' }}</td>
</tr>
@if (opened() === row.patient.id) {
<tr class="stage-detail">
<td colspan="11"><app-stages [stages]="row.stages" [detail]="true" /></td>
</tr>
}
} @empty {
@if (page() && !loading()) {
<tr>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
<td colspan="11" class="muted">No hay registros para los filtros aplicados.</td>
</tr>
}
}
+66 -18
View File
@@ -1,5 +1,13 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import {
Component,
computed,
inject,
input,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -8,7 +16,10 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
import { Row, rows, windowStart } from './follow-up';
import { saveExcel, savePdf } from '../export';
import { Stages } from '../paciente/stages';
import { cytologyResult, followUpSheet } from './follow-up-sheet';
import { bornFor, Row, rows, windowStart } from './follow-up';
import { PatientSearch, patientSearch } from './patient-search';
import { Loading } from '../loading';
import { name } from './measures';
@@ -25,6 +36,7 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
MatInputModule,
MatSelectModule,
RouterLink,
Stages,
],
templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss',
@@ -39,27 +51,31 @@ export class TabRiesgos {
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
protected readonly search = signal('');
protected readonly ageFrom = signal<number | null>(null);
protected readonly ageTo = signal<number | null>(null);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
protected readonly opened = signal<string | undefined>(undefined);
private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES;
protected readonly name = name;
protected readonly result = cytologyResult;
private readonly query = computed(() => ({
'follow-up-window': this.window(),
...patientSearch(this.search()),
birthdate: bornFor(this.cutoff(), this.ageFrom(), this.ageTo()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
}));
private readonly first = resource({
params: () => ({
domain: this.domain(),
'follow-up-window': this.window(),
...patientSearch(this.search()),
'follow-up-cutoff': this.cutoff() || undefined,
'follow-up-status': this.status() || undefined,
'risk-horizon': this.horizon(),
_sort: this.sort(),
_count: this.size(),
}),
loader: ({ params: { domain, ...params } }) => {
params: () => ({ domain: this.domain(), query: this.query(), size: this.size() }),
loader: ({ params: { domain, query, size } }) => {
this.moved.set(undefined);
return this.fhir.search(domain, 'Patient', {
...params,
_revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'],
'_include:iterate': 'DiagnosticReport:result',
});
return this.fhir.search(domain, 'Patient', { ...query, _count: size });
},
});
protected readonly loading = signal(false);
@@ -99,6 +115,38 @@ export class TabRiesgos {
protected retry(): void {
this.first.reload();
}
protected setAge(age: WritableSignal<number | null>, years: number | null): void {
if (!this.cutoff()) this.cutoff.set(this.applied());
age.set(years);
}
protected async save(kind: 'xlsx' | 'pdf'): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
const cutoff = this.applied();
const asked = { ...this.query(), 'follow-up-cutoff': cutoff, _count: 200 };
const pages = await this.fhir.all(this.domain(), 'Patient', asked);
const start = windowStart(cutoff, this.window());
const all = pages.flatMap((p) => rows(p, start, cutoff, this.horizon()));
const sheet = followUpSheet(all, [
['Ventana consultada', `${start} al ${cutoff}`],
['Estatus de seguimiento', this.status() ? name(this.status()) : 'Todos'],
['Edad mínima', `${this.ageFrom() ?? 'Sin límite'}`],
['Edad máxima', `${this.ageTo() ?? 'Sin límite'}`],
['Búsqueda', this.search() || 'Ninguna'],
['Horizonte de la probabilidad (años)', `${this.horizon()}`],
]);
if (kind === 'xlsx') await saveExcel(sheet, 'seguimiento-cacu');
else await savePdf([sheet], 'seguimiento-cacu', true);
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
protected toggle(row: Row): void {
this.opened.set(this.opened() === row.patient.id ? undefined : row.patient.id);
}
protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation);
}