Compare commits

...

2 Commits

Author SHA1 Message Date
Angel Capetillo Zavala c0e4920159 CaCu follow-up list, patient record and exports: stages, filters, risk scales and PDF/XLSX
The list shows five stage nodes per patient with their provenance, filters by age and
search over the whole query, and exports the complete query to PDF and XLSX. The record
shows stage dates and intervals, history, tests and segmented risk scales with markers,
intervals and distinct horizons; absent risks stay unavailable and a zero stays a value.
2026-11-27 18:42:42 -06:00
Angel Capetillo Zavala 31400c77b1 CaCu indicators: HPV genotype, biopsy results, diagnosis timing by ICD-10 and referral PPV cards
The HPV genotype and biopsy distributions, the biopsy request confirmation and the
timing by ICD-10 code are placed beside cytology. The referral PPV cards are titled as
registered procedures and say that a colposcopy may be inferred from notes and that the
preceding cytology is a date association, not a confirmed referral. The new strata and
their values have Spanish labels.
2026-11-27 18:42:41 -06:00
20 changed files with 827 additions and 38 deletions
+5 -3
View File
@@ -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('measure=cacu-eu7') &&
!r.url().includes('%2C'), !r.url().includes('%2C'),
); );
const catalog = page.waitForResponse((r) => r.url().endsWith('/cacu/fhir/Measure'));
await page.goto('/indicadores/cacu'); await page.goto('/indicadores/cacu');
const measures = await (await catalog).json();
const eu7 = await (await report).json(); const eu7 = await (await report).json();
const count = eu7.entry[0].resource.group[0].population.find( const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population', (p: any) => p.code.coding[0].code === 'initial-population',
).count; ).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 expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click(); 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 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?')); const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click(); await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
+20
View File
@@ -0,0 +1,20 @@
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);
}
+44
View File
@@ -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<string, number>): 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();
});
});
+55
View File
@@ -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 };
}
+26 -2
View File
@@ -1,8 +1,32 @@
import type { RiskAssessment } from 'fhir/r4'; import '@angular/compiler';
import { ageGroup, currentRisk, windowStart } from './follow-up'; import { describe, expect, it, vi } from 'vitest';
vi.mock('../plot', () => ({ PALETTE: [] }));
import type { Patient, RiskAssessment } from 'fhir/r4';
import { ageGroup, currentRisk, exactAge, patientLabel, patientName, rows, windowStart } from './follow-up';
import { periods } from './measures'; import { periods } from './measures';
describe('follow-up list', () => { 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)', () => { 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-11-22', 3)).toBe('2026-08-23');
expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one expect(windowStart('2026-05-31', 3)).toBe('2026-03-01'); // 2026-02-28, plus one
+41 -5
View File
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir'; 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. */ /** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row { export interface Row {
@@ -8,7 +9,9 @@ export interface Row {
curp?: string; curp?: string;
status: string; status: string;
ageGroup: 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 }; hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number; daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string }; biopsy?: { date: string; histology?: string };
@@ -17,6 +20,36 @@ export interface Row {
export const CURP = 'https://isssteleon.org/fhir/sid/curp'; 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][] = [ const AGE_GROUPS: [number, number][] = [
[25, 34], [25, 34],
[35, 44], [35, 44],
@@ -49,7 +82,7 @@ export function currentRisk(
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`)) .filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) => .flatMap((r) =>
(r.prediction ?? []) (r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon) .filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
.map((p) => ({ r, p })), .map((p) => ({ r, p })),
); );
if (!mine.length) return undefined; if (!mine.length) return undefined;
@@ -60,7 +93,7 @@ export function currentRisk(
return Math.max( return Math.max(
...mine ...mine
.filter((x) => x.r.occurrenceDateTime === latest) .filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal ?? 0), .map((x) => x.p.probabilityDecimal!),
); );
} }
@@ -99,12 +132,15 @@ export function rows(page: Bundle, start: string, cutoff: string, horizon: numbe
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`); const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return { return {
patient, patient,
name: patient.name?.[0]?.text, name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff), ageGroup: ageGroup(patient.birthDate, cutoff),
age: exactAge(patient.birthDate, cutoff),
stageFacts: routeFacts(last),
cytology: last && { cytology: last && {
date: last.effectiveDateTime!, date: last.effectiveDateTime!,
reportDate: ext(last, 'report-date')?.valueDate,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept), result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept), adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
}, },
@@ -186,7 +222,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1); .at(-1);
return { return {
patient, patient,
name: patient.name?.[0]?.text, name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value, curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '', status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '', priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
+23
View File
@@ -44,12 +44,14 @@ export function periodTypes(measure: Measure): PeriodType[] {
/** What one report says: its counts, its score and interval, and its strata. */ /** What one report says: its counts, its score and interval, and its strata. */
export interface Reading { export interface Reading {
error?: boolean;
populations: Record<string, number>; populations: Record<string, number>;
score?: number; score?: number;
low?: number; low?: number;
high?: number; high?: number;
unit?: string; unit?: string;
strata: Record<string, Record<string, Record<string, number>>>; strata: Record<string, Record<string, Record<string, number>>>;
stratumScores?: Record<string, Record<string, { median: number; low?: number; high?: number }>>;
} }
function counts(group: { function counts(group: {
@@ -65,11 +67,13 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
if (!group) return undefined; if (!group) return undefined;
const score = group.measureScore; const score = group.measureScore;
const strata: Reading['strata'] = {}; const strata: Reading['strata'] = {};
const stratumScores: NonNullable<Reading['stratumScores']> = {};
for (const s of group.stratifier ?? []) { for (const s of group.stratifier ?? []) {
const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? ''; const name = code(s.code?.[0]) ?? s.code?.[0]?.text ?? '';
strata[name] = Object.fromEntries( strata[name] = Object.fromEntries(
(s.stratum ?? []).map((x) => [x.value?.text ?? '', counts(x)]), (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 { return {
populations: counts(group), populations: counts(group),
@@ -78,6 +82,7 @@ export function reading(report: MeasureReport | undefined): Reading | undefined
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal, high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
unit: score?.unit, unit: score?.unit,
strata, strata,
stratumScores,
}; };
} }
@@ -116,6 +121,13 @@ const LABELS: Record<string, string> = {
good: 'Bueno', good: 'Bueno',
bad: 'Malo', bad: 'Malo',
not_analyzed: 'Sin analizar', 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( ...Object.fromEntries(
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]), ['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
), ),
@@ -128,7 +140,18 @@ export const STRATA: Record<string, string> = {
follow_up_status: 'Estatus de seguimiento', follow_up_status: 'Estatus de seguimiento',
result: 'Citología de alto grado', result: 'Citología de alto grado',
birads: 'BI-RADS de la mastografía', 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<string, { title: string; note: string }> = {
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 const name = (value: string) => LABELS[value] ?? value;
export function formatScore(measure: Measure, r: Reading | undefined): string { export function formatScore(measure: Measure, r: Reading | undefined): string {
+33
View File
@@ -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');
});
});
+154 -3
View File
@@ -52,7 +52,7 @@
@if (layout().route.length) { @if (layout().route.length) {
<mat-card appearance="outlined" class="route"> <mat-card appearance="outlined" class="route">
<mat-card-header> <mat-card-header>
<mat-card-title>Ruta del tamizaje</mat-card-title> <mat-card-title>{{ domain() === 'cacu' ? 'Tiempos de la ruta del tamizaje' : 'Ruta del tamizaje' }}</mat-card-title>
<mat-button-toggle-group <mat-button-toggle-group
[value]="routeView()" [value]="routeView()"
(change)="routeView.set($event.value)" (change)="routeView.set($event.value)"
@@ -60,21 +60,172 @@
> >
<mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle> <mat-button-toggle value="sample">Acumulado desde la toma</mat-button-toggle>
<mat-button-toggle value="step">Por pasos</mat-button-toggle> <mat-button-toggle value="step">Por pasos</mat-button-toggle>
@if (domain() === 'cacu') { <mat-button-toggle value="icd10">Desglose por CIE-10</mat-button-toggle> }
</mat-button-toggle-group> </mat-button-toggle-group>
</mat-card-header> </mat-card-header>
<mat-card-content> <mat-card-content>
<app-plot [figure]="route()" [height]="260" /> @if (domain() !== 'cacu') { <app-plot [figure]="route()" [height]="260" /> }
@else if (routeView() === 'icd10') {
<p class="muted">Desglose exploratorio basado en la asociación temporal existente; no confirma un vínculo clínico entre la toma y el diagnóstico.</p>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (icd(); as r) {
<p class="muted">{{ r.populations['measure-observation'] ?? 0 }} observaciones · escala 0 a {{ icdMax() }} días.</p>
<table class="distribution route-table" aria-label="Tiempos por CIE-10"><thead><tr><th>CIE-10 y descripción</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead><tbody>
@for (row of icdRows(); track row.label) {
<tr><th scope="row">{{ row.label }}<span class="bar-track duration-track" aria-hidden="true"><span class="bar" [style.width.%]="icdMax() ? 100 * row.median / icdMax() : 0"></span><span class="quartile" [style.left.%]="icdMax() ? 100 * (row.low ?? 0) / icdMax() : 0"></span><span class="quartile" [style.left.%]="icdMax() ? 100 * (row.high ?? 0) / icdMax() : 0"></span></span></th><td>{{ row.median }} días</td><td>{{ row.count }}</td><td>{{ row.low }}–{{ row.high }}</td></tr>
} @empty { <tr><td colspan="4">Sin observaciones en el periodo.</td></tr> }
</tbody></table>
} @else { <p class="muted">Desglose no disponible en este servidor o periodo.</p> }
} @else {
@if (routeView() === 'step') {
<p class="muted">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.</p>
<app-plot [figure]="stepRoute()" [height]="stepRouteHeight()" />
<details class="route-values">
<summary>Cuartiles y valores por tramo</summary>
<p class="muted">Q1, mediana y Q3 corresponden a las observaciones disponibles de cada tramo. Los tramos sin datos se indican como no disponibles.</p>
<table class="distribution route-table" aria-label="Valores estadísticos de tiempos por tramo">
<thead><tr><th>Tramo</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead>
<tbody>@for (row of routeRows(); track row.label) {
<tr><th scope="row">{{ row.label }}</th><td>{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}</td>
<td>{{ row.reading?.score !== undefined ? (row.reading?.populations?.['measure-observation'] ?? '—') : '—' }}</td>
<td>{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}</td></tr>
}</tbody>
</table>
</details>
} @else {
<p class="muted">Escala: 0 a {{ routeMax() }} días. Las marcas indican el primer y tercer cuartil.</p>
<table class="distribution route-table" aria-label="Tiempos de la ruta del tamizaje">
<thead><tr><th>Etapa</th><th>Mediana</th><th>Observaciones</th><th>Q1–Q3</th></tr></thead>
<tbody>
@for (row of routeRows(); track row.label) {
<tr><th scope="row">{{ row.label }}
@if (row.reading?.score !== undefined) {
<span class="bar-track duration-track" aria-hidden="true">
<span class="bar" [style.width.%]="routeMax() ? 100 * row.reading!.score! / routeMax() : 0"></span>
@if (row.reading!.low !== undefined && row.reading!.high !== undefined) {
<span class="quartile" [style.left.%]="routeMax() ? 100 * row.reading!.low! / routeMax() : 0"></span>
<span class="quartile" [style.left.%]="routeMax() ? 100 * row.reading!.high! / routeMax() : 0"></span>
}
</span>
}
</th><td>{{ row.reading?.score !== undefined ? row.reading!.score + ' días' : '—' }}</td>
<td>{{ row.reading?.populations?.['measure-observation'] ?? '—' }}</td>
<td>{{ row.reading?.low !== undefined && row.reading?.high !== undefined ? row.reading!.low + '–' + row.reading!.high : '—' }}</td></tr>
}
</tbody>
</table>
}
}
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
} }
<h2>Indicadores clínicos</h2> <h2>Indicadores clínicos</h2>
@if (domain() === 'cacu') {
<mat-card appearance="outlined" class="results-card">
<mat-card-header><mat-card-title>Resultados de citología, VPH y biopsia</mat-card-title></mat-card-header>
<mat-card-content class="results-grid">
<section aria-labelledby="cytology-title">
<h3 id="cytology-title">Distribución de resultados citológicos</h3>
@if (reports.isLoading()) {
<p class="muted">Calculando…</p>
} @else if (cytology(); as distribution) {
<p class="muted">{{ distribution.total }} pacientes con resultado elegible · {{ distribution.outside }} fuera de la distribución</p>
<p class="muted">Una muestra por paciente en el periodo; se prioriza la última válida. Los porcentajes usan los resultados elegibles.</p>
<p class="muted">Escala de las barras: 0 a {{ distribution.max }} pacientes.</p>
<table class="distribution" aria-label="Distribución de resultados citológicos">
<thead><tr><th>Categoría</th><th>Pacientes</th><th>%</th></tr></thead>
<tbody>
@for (row of distribution.rows; track row.label) {
<tr>
<th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="distribution.max ? 100 * row.count / distribution.max : 0" [style.background]="row.color"></span></span></th>
<td>{{ row.count }}</td>
<td>{{ distribution.total ? (100 * row.count / distribution.total).toFixed(1) + ' %' : '—' }}</td>
</tr>
}
</tbody>
</table>
@if (!distribution.total) { <p class="muted">Sin resultados elegibles en el periodo.</p> }
} @else {
<p class="muted">{{ hasCytologyMeasure() ? 'Distribución no disponible para este periodo.' : 'Medida no publicada por el servidor.' }}</p>
}
</section>
<section aria-labelledby="hpv-title">
<h3 id="hpv-title">Resultados de VPH por genotipo</h3>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (hpv(); as d) {
<p class="muted">{{ d.total }} reportes VPH elegibles · periodo por fecha de toma. {{ d.outside }} fuera de las categorías mostradas.</p>
<p class="muted">Escala de las barras: 0 a {{ d.max }} reportes. El contrato actual no representa resultados indeterminados.</p>
<table class="distribution" aria-label="Resultados de VPH por genotipo">
<thead><tr><th>Categoría</th><th>Reportes</th><th>%</th></tr></thead>
<tbody>
@for (row of d.rows; track row.label) {
@if (row.label === 'No clasificable o inconsistente') { <tr><th scope="row">Indeterminado</th><td colspan="2">No disponible en el contrato actual</td></tr> }
<tr><th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="d.max ? 100 * row.count / d.max : 0" [style.background]="row.color"></span></span></th>
<td>{{ row.count }}</td><td>{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}</td></tr>
}
</tbody>
</table>
@if (!d.total) { <p class="muted">Sin reportes elegibles en el periodo.</p> }
} @else { <p class="muted">{{ hasHpvMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución no publicada por el servidor.' }}</p> }
</section>
<section class="biopsy" aria-labelledby="biopsy-title">
<h3 id="biopsy-title">Resultado de la biopsia</h3>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (biopsy(); as d) {
<p class="muted">{{ d.total }} reportes con histología clasificable · periodo por fecha de reporte.</p>
<p class="muted">{{ d.noData }} reportes sin grado · {{ d.outside - d.noData }} con grado no clasificable. Las órdenes sin reporte no están incluidas.</p>
<p class="muted">Escala de las barras: 0 a {{ d.max }} reportes.</p>
<table class="distribution" aria-label="Resultados de biopsia cervical">
<thead><tr><th>Categoría</th><th>Reportes</th><th>%</th></tr></thead>
<tbody>
@for (row of d.rows; track row.label; let i = $index) {
@if (i === 0) { <tr class="group"><th scope="rowgroup" colspan="3">Menor que LIEAG · {{ d.rows[0].count + d.rows[1].count }}</th></tr> }
@if (i === 2) { <tr class="group"><th scope="rowgroup" colspan="3">LIEAG o más · {{ d.rows[2].count + d.rows[3].count + d.rows[4].count }}</th></tr> }
<tr><th scope="row"><span class="distribution-label">{{ row.label }}</span><span class="bar-track" aria-hidden="true"><span class="bar" [style.width.%]="d.max ? 100 * row.count / d.max : 0" [style.background]="row.color"></span></span></th>
<td>{{ row.count }}</td><td>{{ d.total ? (100 * row.count / d.total).toFixed(1) + ' %' : '—' }}</td></tr>
}
</tbody>
</table>
@if (!d.total) { <p class="muted">Sin reportes con grado clasificable en el periodo.</p> }
} @else { <p class="muted">{{ hasBiopsyMeasure() ? 'Distribución no disponible para este periodo.' : 'Distribución general no publicada por el servidor.' }}</p> }
</section>
</mat-card-content>
</mat-card>
<div class="confirmation-cards">
<mat-card appearance="outlined"><mat-card-header><mat-card-title>Tasa de confirmación histopatológica de referencia a colposcopia</mat-card-title></mat-card-header>
<mat-card-content><p>No disponible: no se identifican las referencias emitidas a colposcopia. Las colposcopias inferidas no acreditan ese denominador.</p></mat-card-content>
</mat-card>
<mat-card appearance="outlined"><mat-card-header><mat-card-title>Tasa de confirmación histopatológica de referencia a biopsia</mat-card-title></mat-card-header>
<mat-card-content>
<p>La tasa de referencias emitidas no está disponible: no se acreditó la cobertura de referencias ni las cancelaciones.</p>
<p class="muted">Aproximación distinta: estudios con solicitud de biopsia registrada, por fecha de solicitud.</p>
@if (reports.isLoading()) { <p class="muted">Calculando…</p> }
@else if (!requestsMeasure()) { <p>No disponible: medida no publicada por el servidor.</p> }
@else if (requests()?.error) { <p role="alert">Error al consultar las solicitudes de biopsia.</p> }
@else if (requests(); as r) {
@if (validRequests()) {
@if (r.populations['initial-population']; as total) {
<p>Denominador: {{ total }} solicitudes registradas (no pacientes).</p>
<p>LIEAG o más: {{ category(r, 'high_grade') }} / {{ total }} · {{ (100 * category(r, 'high_grade') / total).toFixed(1) }} %</p>
<p>Menor que LIEAG: {{ category(r, 'below_high_grade') }} / {{ total }} · {{ (100 * category(r, 'below_high_grade') / total).toFixed(1) }} %</p>
<p class="muted">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') }}.</p>
} @else { <p>Sin solicitudes registradas en el periodo; porcentaje no calculable (denominador 0).</p> }
} @else { <p role="alert">Los datos de solicitudes recibidos están incompletos o son inconsistentes.</p> }
} @else { <p>No disponible para este periodo.</p> }
</mat-card-content>
</mat-card>
</div>
}
<div class="clinical"> <div class="clinical">
@for (m of clinical(); track m.id) { @for (m of clinical(); track m.id) {
<mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name"> <mat-card appearance="outlined" class="clinical-card" [attr.data-measure]="m.name">
<mat-card-header> <mat-card-header>
<mat-card-title>{{ m.title }}</mat-card-title> <mat-card-title>{{ measureTitle(m) }}</mat-card-title>
<mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle> <mat-card-subtitle>{{ score(m) }} · {{ detail(m) }}</mat-card-subtitle>
@if (ppvNote(m); as note) { <mat-card-subtitle class="ppv-note">{{ note }}</mat-card-subtitle> }
@if (domain() === 'cacu' && m.name === 'CACU_EU7') { <mat-card-subtitle>El tamizaje inicial o subsecuente es el que declara el formulario o se deduce de la ruta; «Sin dato» si no consta.</mat-card-subtitle> }
@if (domain() === 'cacu' && m.name === 'CACU_CONFIRMACION_CITOLOGIA') { <mat-card-subtitle>Pacientes con citología ASC-H, LIEAG o carcinoma in situ; incluye casos sin biopsia.</mat-card-subtitle> }
</mat-card-header> </mat-card-header>
<mat-card-content> <mat-card-content>
@for (f of figureSets().get(m.name!) ?? []; track f.title) { @for (f of figureSets().get(m.name!) ?? []; track f.title) {
+35
View File
@@ -78,11 +78,46 @@ h2 {
gap: var(--space-3); gap: var(--space-3);
justify-content: space-between; 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 { .clinical {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
grid-template-columns: 1fr; 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) { @media (min-width: 1304px) {
+87 -2
View File
@@ -8,6 +8,7 @@ import type { Measure, MeasureReport } from 'fhir/r4';
import { Fhir, resources } from '../fhir'; import { Fhir, resources } from '../fhir';
import { Figure, Plot } from '../plot'; import { Figure, Plot } from '../plot';
import { LAYOUTS } from './layout'; import { LAYOUTS } from './layout';
import { biopsyDistribution, cytologyDistribution, hpvDistribution } from './cacu-results';
import { import {
detail, detail,
donut, donut,
@@ -21,6 +22,8 @@ import {
Reading, Reading,
scoring, scoring,
STRATA, STRATA,
PPV_NOTES,
measureTitle,
strataBars, strataBars,
} from './measures'; } from './measures';
@@ -49,7 +52,7 @@ export class TabIndicadores {
protected readonly chosen = signal<string | undefined>(undefined); protected readonly chosen = signal<string | undefined>(undefined);
/** The period the figures show (set by Aplicar). */ /** The period the figures show (set by Aplicar). */
protected readonly applied = signal<string | undefined>(undefined); protected readonly applied = signal<string | undefined>(undefined);
protected readonly routeView = signal<'sample' | 'step'>('sample'); protected readonly routeView = signal<'sample' | 'step' | 'icd10'>('sample');
protected readonly layout = computed( protected readonly layout = computed(
() => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' }, () => LAYOUTS[this.domain()] ?? { kpis: [], route: [], anchor: '' },
@@ -64,6 +67,7 @@ export class TabIndicadores {
const placed = new Set([ const placed = new Set([
...this.layout().kpis, ...this.layout().kpis,
...this.layout().route.flatMap((s) => [s.fromSample, s.fromStep]), ...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!)); return this.measures().filter((m) => !placed.has(m.name!));
}); });
@@ -94,11 +98,19 @@ export class TabIndicadores {
if (!params.period) return new Map<string, Reading | undefined>(); if (!params.period) return new Map<string, Reading | undefined>();
const found = await Promise.all( const found = await Promise.all(
params.measures.map(async (m) => { params.measures.map(async (m) => {
try {
const page = await this.fhir.search(params.domain, 'MeasureReport', { const page = await this.fhir.search(params.domain, 'MeasureReport', {
measure: m.id!, measure: m.id!,
'reporting-period': params.period, 'reporting-period': params.period,
}); });
return [m.name!, reading(resources<MeasureReport>(page, 'MeasureReport')[0])] as const; return [m.name!, reading(resources<MeasureReport>(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); 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<Figure>(() => {
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}<br>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}<br>Mediana del tramo: %{x} días<extra></extra>' }],
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. */ /** Each clinical card's figures, built once per loaded period. */
protected readonly figureSets = computed( 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. */ /** A clinical card's figures: the overall split, then one per stratum. */
private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] { private build(m: Measure, r: Reading | undefined): { title: string; figure: Figure }[] {
if (!r || !(r.populations['initial-population'] ?? 0)) return []; if (!r || !(r.populations['initial-population'] ?? 0)) return [];
@@ -160,7 +239,9 @@ export class TabIndicadores {
if (kind === 'continuous-variable') if (kind === 'continuous-variable')
return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }]; return [{ title: 'Mediana y cuartiles', figure: medians([{ label: m.title!, r }]) }];
return [ 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) => ({ ...strata.map((s) => ({
title: `Por ${STRATA[s]?.toLowerCase() ?? s}`, title: `Por ${STRATA[s]?.toLowerCase() ?? s}`,
figure: strataBars(m, r, s), figure: strataBars(m, r, s),
@@ -168,4 +249,8 @@ export class TabIndicadores {
]; ];
} }
protected readonly name = name; protected readonly name = name;
protected readonly measureTitle = measureTitle;
protected ppvNote(m: Measure): string | undefined {
return PPV_NOTES[m.name ?? '']?.note;
}
} }
+20 -7
View File
@@ -1,4 +1,12 @@
<div class="export-actions"><button mat-stroked-button (click)="exportList('xlsx')" [disabled]="exporting() || !page() || invalidAge() || queryLoading() || loading()">Exportar Excel (.xlsx)</button><button mat-stroked-button (click)="exportList('pdf')" [disabled]="exporting() || !page() || invalidAge() || queryLoading() || loading()">Exportar PDF</button></div>
@if (exportMessage()) { <p role="alert">{{ exportMessage() }}</p> }
<form class="filters card" (submit)="$event.preventDefault()"> <form class="filters card" (submit)="$event.preventDefault()">
@if (globalFilters()) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Buscar nombre o identificador</mat-label><input matInput [ngModel]="search()" (ngModelChange)="search.set($event)" name="search" /></mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Edad mínima</mat-label><input matInput type="number" min="0" max="150" step="1" [ngModel]="ageMin()" (ngModelChange)="ageMin.set($event)" name="ageMin" /></mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Edad máxima</mat-label><input matInput type="number" min="0" max="150" step="1" [ngModel]="ageMax()" (ngModelChange)="ageMax.set($event)" name="ageMax" /></mat-form-field>
<button mat-stroked-button type="button" (click)="ageMin.set(null); ageMax.set(null)">Limpiar edades</button>
}
<mat-form-field appearance="outline" subscriptSizing="dynamic"> <mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Fecha de corte</mat-label> <mat-label>Fecha de corte</mat-label>
<input <input
@@ -38,7 +46,7 @@
<mat-label>Orden</mat-label> <mat-label>Orden</mat-label>
<mat-select [value]="sort()" (selectionChange)="sort.set($event.value)"> <mat-select [value]="sort()" (selectionChange)="sort.set($event.value)">
<mat-option value="-recent">Estudio más reciente</mat-option> <mat-option value="-recent">Estudio más reciente</mat-option>
<mat-option value="-risk-cin2">Mayor riesgo de LIEAG+</mat-option> <mat-option value="-risk-cin2">Mayor riesgo de CIN2+</mat-option>
<mat-option value="-risk-cancer">Mayor riesgo de cáncer</mat-option> <mat-option value="-risk-cancer">Mayor riesgo de cáncer</mat-option>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
@@ -51,6 +59,8 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
</form> </form>
@if (invalidAge()) { <p role="alert">Indique edades enteras entre 0 y 150; la mínima no puede superar la máxima. El rango no está aplicado.</p> }
@if (!globalFilters() && !capabilities.isLoading()) { <p class="muted">El servidor no declara búsqueda global ni filtros de edad.</p> }
@if (error()) { @if (error()) {
<p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p> <p class="muted" role="alert">No se pudo leer la lista de seguimiento.</p>
@@ -61,12 +71,13 @@
<thead> <thead>
<tr> <tr>
<th>Paciente</th> <th>Paciente</th>
<th>Grupo de edad</th> <th>Edad</th>
<th>Estatus</th> <th>Estatus</th>
<th>Etapas</th>
<th>Última citología</th> <th>Última citología</th>
<th>VPH</th> <th>VPH</th>
<th>Biopsia</th> <th>Biopsia</th>
<th>Riesgo LIEAG+ ({{ horizon() }} a)</th> <th>Riesgo CIN2+ ({{ horizon() }} a)</th>
<th>Riesgo cáncer ({{ horizon() }} a)</th> <th>Riesgo cáncer ({{ horizon() }} a)</th>
<th>Días toma → diagnóstico</th> <th>Días toma → diagnóstico</th>
</tr> </tr>
@@ -75,15 +86,16 @@
@for (row of rows(); track row.patient.id) { @for (row of rows(); track row.patient.id) {
<tr> <tr>
<td> <td>
<a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]">{{ <a [routerLink]="['/indicadores', domain(), 'pacientes', row.patient.id]" [queryParams]="{ corte: applied(), muestra: row.cytology?.date }">{{
row.name ?? row.patient.id!.slice(0, 10) patientLabel(row.patient)
}}</a> }}</a>
@if (row.curp) { @if (row.curp) {
<div class="muted curp">{{ row.curp }}</div> <div class="muted curp">{{ row.curp }}</div>
} }
</td> </td>
<td>{{ row.ageGroup }}</td> <td>{{ row.age ?? 'No disponible' }}</td>
<td>{{ name(row.status) }}</td> <td>{{ name(row.status) }}</td>
<td><div class="stage-compact"><app-stages [sample]="row.cytology?.date" [report]="row.cytology?.result ? row.cytology?.reportDate : undefined" [cutoff]="applied()" [facts]="row.stageFacts" /><button class="stage-toggle" type="button" [attr.aria-label]="expanded() === row.patient.id ? 'Ocultar etapas' : 'Mostrar etapas'" [attr.aria-expanded]="expanded() === row.patient.id" (click)="expanded.set(expanded() === row.patient.id ? undefined : row.patient.id)"><span [class.open]="expanded() === row.patient.id" aria-hidden="true">⌄</span></button></div></td>
<td> <td>
@if (row.cytology; as c) { @if (row.cytology; as c) {
{{ c.date }} · {{ c.date }} ·
@@ -122,9 +134,10 @@
</td> </td>
<td class="num">{{ row.daysToDiagnosis ?? '—' }}</td> <td class="num">{{ row.daysToDiagnosis ?? '—' }}</td>
</tr> </tr>
@if (expanded() === row.patient.id) { <tr><td colspan="10"><app-stages [sample]="row.cytology?.date" [report]="row.cytology?.result ? row.cytology?.reportDate : undefined" [cutoff]="applied()" [facts]="row.stageFacts" [detail]="true" /></td></tr> }
} @empty { } @empty {
<tr> <tr>
<td colspan="9" class="muted"> <td colspan="10" class="muted">
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }} {{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
</td> </td>
</tr> </tr>
+5
View File
@@ -40,3 +40,8 @@ a {
.pager .muted { .pager .muted {
margin-right: auto; margin-right: auto;
} }
.export-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-bottom: 12px; }
.stage-compact { display:flex; align-items:center; gap:0; }
.stage-toggle { display:grid; place-items:center; flex:0 0 32px; width:32px; height:32px; border:0; background:transparent; color:#385c6c; cursor:pointer; padding:0; }
.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); }
+69 -2
View File
@@ -8,8 +8,13 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { rows, windowStart } from './follow-up'; import { patientLabel, rows, windowStart } from './follow-up';
import { name } from './measures'; import { name } from './measures';
import { Stages } from '../paciente/stages';
import { stages } from '../paciente/stages';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { downloadDocument } from '../export-document';
const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']; const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment'];
@@ -25,12 +30,16 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
MatInputModule, MatInputModule,
MatSelectModule, MatSelectModule,
RouterLink, RouterLink,
Stages,
], ],
templateUrl: './tab-riesgos.html', templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss', styleUrl: './tab-riesgos.scss',
}) })
export class TabRiesgos { export class TabRiesgos {
private readonly fhir = inject(Fhir); private readonly fhir = inject(Fhir);
private readonly http = inject(HttpClient);
protected readonly exporting = signal(false);
protected readonly exportMessage = signal('');
readonly domain = input.required<string>(); readonly domain = input.required<string>();
protected readonly cutoff = signal<string>(''); protected readonly cutoff = signal<string>('');
@@ -39,11 +48,29 @@ export class TabRiesgos {
protected readonly horizon = signal(5); protected readonly horizon = signal(5);
protected readonly sort = signal('-recent'); protected readonly sort = signal('-recent');
protected readonly size = signal(20); protected readonly size = signal(20);
protected readonly ageMin = signal<number | null>(null);
protected readonly ageMax = signal<number | null>(null);
protected readonly search = signal('');
protected readonly expanded = signal<string | undefined>(undefined);
protected readonly invalidAge = computed(() => {
const a = this.ageMin(), b = this.ageMax();
return [a,b].some(n => n !== null && (!Number.isInteger(n) || n < 0 || n > 150)) || (a !== null && b !== null && a > b);
});
protected readonly capabilities = resource({
params: () => this.domain(),
loader: async ({params}) => this.fhir.search(params, 'metadata') as Promise<any>,
});
protected readonly globalFilters = computed(() => {
const patient = this.capabilities.value()?.rest?.flatMap((r: any) => r.resource ?? []).find((r: any) => r.type === 'Patient');
const names = new Set<string>((patient?.searchParam ?? []).map((x: any) => x.name));
return ['follow-up-age-min','follow-up-age-max','follow-up-search'].every(n => names.has(n));
});
/** A page the user moved to (`next`/`previous`), else the first. */ /** A page the user moved to (`next`/`previous`), else the first. */
private readonly moved = signal<Bundle | undefined>(undefined); private readonly moved = signal<Bundle | undefined>(undefined);
protected readonly statuses = STATUSES; protected readonly statuses = STATUSES;
protected readonly name = name; protected readonly name = name;
protected readonly patientLabel = patientLabel;
private readonly first = resource({ private readonly first = resource({
params: () => ({ params: () => ({
@@ -54,6 +81,9 @@ export class TabRiesgos {
'risk-horizon': this.horizon(), 'risk-horizon': this.horizon(),
_sort: this.sort(), _sort: this.sort(),
_count: this.size(), _count: this.size(),
'follow-up-age-min': this.globalFilters() && !this.invalidAge() ? this.ageMin() ?? undefined : undefined,
'follow-up-age-max': this.globalFilters() && !this.invalidAge() ? this.ageMax() ?? undefined : undefined,
'follow-up-search': this.globalFilters() ? this.search().trim().replace(/\s+/g, ' ') || undefined : undefined,
}), }),
loader: ({ params: { domain, ...params } }) => { loader: ({ params: { domain, ...params } }) => {
this.moved.set(undefined); this.moved.set(undefined);
@@ -65,6 +95,7 @@ export class TabRiesgos {
}, },
}); });
protected readonly loading = signal(false); protected readonly loading = signal(false);
protected readonly queryLoading = computed(() => this.first.isLoading());
protected readonly page = computed(() => this.moved() ?? this.first.value()); protected readonly page = computed(() => this.moved() ?? this.first.value());
/** The cut-off as applied (the server's default when none is given). */ /** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => { protected readonly applied = computed(() => {
@@ -84,6 +115,40 @@ export class TabRiesgos {
}); });
protected readonly error = computed(() => this.first.error()); protected readonly error = computed(() => this.first.error());
protected async exportList(format: 'xlsx' | 'pdf'): Promise<void> {
if (!this.page() || this.invalidAge() || !this.applied() || this.queryLoading() || this.loading()) return;
const total = this.page()!.total ?? 0, limit = format === 'pdf' ? 1000 : 5000;
if (total > limit) { this.exportMessage.set(`La consulta tiene ${total} pacientes; el límite para ${format.toUpperCase()} es ${limit}. Ajuste los filtros.`); return; }
const cutoff = this.applied(), months = this.window(), horizon = this.horizon();
const params = {'follow-up-window': months, 'follow-up-cutoff': cutoff, 'follow-up-status': this.status() || undefined,
'risk-horizon': horizon, _sort: this.sort(), _count: 200,
'follow-up-age-min': this.globalFilters() ? this.ageMin() ?? undefined : undefined,
'follow-up-age-max': this.globalFilters() ? this.ageMax() ?? undefined : undefined,
'follow-up-search': this.globalFilters() ? this.search().trim().replace(/\s+/g,' ') || undefined : undefined,
_revinclude: ['DiagnosticReport:subject','RiskAssessment:subject'], '_include:iterate':'DiagnosticReport:result'};
this.exporting.set(true); this.exportMessage.set('');
try {
const caps = await firstValueFrom(this.http.get<{xlsx_limit:number;pdf_limit:number}>('/api/cacu/exports/capabilities'));
if (total > (format === 'pdf' ? caps.pdf_limit : caps.xlsx_limit)) throw new Error('La consulta supera el límite del servidor.');
const pages = await this.fhir.all(this.domain(), 'Patient', params);
const all = pages.flatMap(page => rows(page, 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.');
const pct = (n?: number) => n === undefined ? 'No disponible' : `${(100*n).toFixed(1)} %`;
const sortLabels: Record<string,string> = {'-recent':'Estudio más reciente','-risk-cin2':'Mayor riesgo de CIN2+','-risk-cancer':'Mayor riesgo de cáncer'};
const routes = all.map(r => stages(r.cytology?.date,r.cytology?.result ? r.cytology.reportDate : undefined,cutoff,r.stageFacts));
await downloadDocument(this.http, format, {title:'Resultados de seguimiento', parameters:[['Fecha de corte',cutoff],['Ventana consultada',`${windowStart(cutoff,months)} al ${cutoff} (${months} ${months === 1 ? 'mes' : 'meses'})`],['Estatus de seguimiento',params['follow-up-status'] ? name(params['follow-up-status']) : 'Todos'],['Orden',sortLabels[params._sort] ?? params._sort],['Horizonte de la probabilidad',`${horizon} ${horizon === 1 ? 'año' : 'años'}`],['Nombre o identificador contiene',params['follow-up-search'] || 'Todos'],['Edad mínima (años)',String(params['follow-up-age-min'] ?? 'Sin límite')],['Edad máxima (años)',String(params['follow-up-age-max'] ?? 'Sin límite')],['Registros',String(total)]],
columns:['Paciente','Edad','Estatus','Etapas','Última citología','VPH','Biopsia','Riesgo CIN2+','Riesgo cáncer','Días 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 : ''}`,String(r.age ?? 'No disponible'),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'}` : '—',
r.hpv ? `${r.hpv.positive ? 'Positivo' : 'Negativo'}${r.hpv.types1618 ? ' (16/18)' : ''}` : '—',
r.biopsy ? `${r.biopsy.date} · ${name(r.biopsy.histology ?? '') || 'Sin dato'}` : '—',pct(r.risk.cin2),pct(r.risk.cancer),String(r.daysToDiagnosis ?? '—')])});
} catch (error) { this.exportMessage.set(error instanceof Error ? error.message : 'No se pudo generar la exportación.'); }
finally { this.exporting.set(false); }
}
protected has(relation: 'next' | 'previous'): boolean { protected has(relation: 'next' | 'previous'): boolean {
return !!this.page()?.link?.some((l) => l.relation === relation); return !!this.page()?.link?.some((l) => l.relation === relation);
} }
@@ -93,8 +158,10 @@ export class TabRiesgos {
const next = page && this.fhir.follow(this.domain(), page, relation); const next = page && this.fhir.follow(this.domain(), page, relation);
if (!next) return; if (!next) return;
this.loading.set(true); this.loading.set(true);
const signature = JSON.stringify([this.cutoff(), this.window(), this.status(), this.horizon(), this.sort(), this.size(), this.ageMin(), this.ageMax(), this.search()]);
try { try {
this.moved.set(await next); const found = await next;
if (signature === JSON.stringify([this.cutoff(), this.window(), this.status(), this.horizon(), this.sort(), this.size(), this.ageMin(), this.ageMax(), this.search()])) this.moved.set(found);
} finally { } finally {
this.loading.set(false); this.loading.set(false);
} }
+23 -2
View File
@@ -1,4 +1,6 @@
<section class="page"> <section class="page">
@if (domain() === 'cacu' && patient()) { <div class="export-actions"><button mat-stroked-button [disabled]="exporting()" (click)="exportPatient()">Exportar ficha PDF</button></div> }
@if (exportError()) { <p role="alert">{{ exportError() }}</p> }
<a mat-button [routerLink]="['/indicadores', domain()]" <a mat-button [routerLink]="['/indicadores', domain()]"
><mat-icon>arrow_back</mat-icon> Regresar</a ><mat-icon>arrow_back</mat-icon> Regresar</a
> >
@@ -6,7 +8,8 @@
<p class="muted" role="alert">No se encontró la paciente.</p> <p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) { } @else if (patient(); as p) {
<h1> <h1>
{{ identity().name ?? 'Paciente' }} <code class="muted">{{ p.id!.slice(0, 10) }}</code> {{ identity().name ?? p.id?.slice(0, 10) ?? 'No disponible' }} @if (identity().name && p.id) { <code class="muted">{{ p.id.slice(0, 10) }}</code> }
@if (domain() === 'cacu') { · Edad: {{ exactAge(p.birthDate, cutoff) ?? 'No disponible' }} }
</h1> </h1>
<dl class="summary"> <dl class="summary">
<div> <div>
@@ -43,6 +46,7 @@
<mat-card appearance="outlined"> <mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content> <mat-card-content>
@if (domain() === 'cacu') { <app-stages [sample]="sample" [report]="sampleReportDate()" [cutoff]="cutoff" [facts]="sampleFacts()" [detail]="true" /> }
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
@@ -108,7 +112,24 @@
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header ><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
> >
<mat-card-content> <mat-card-content>
@if (models().length) { @if (domain() === 'cacu') {
<p class="muted">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
@for (model of riskScales(); track model.model) {
<h3>{{ model.outcome }} · {{ model.model }} · fecha índice {{ model.index }}</h3>
@for (scale of [{label: 'Riesgo inmediato (al índice)', value: model.immediate}, {label: 'Riesgo a 5 años', value: model.five}]; track scale.label) {
<div class="risk-scale">
<p><strong>{{ scale.label }}</strong> @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 }</p>
<div class="risk-plot" [class.unavailable]="!scale.value"><div class="risk-line" aria-hidden="true"></div>@if (scale.value; as v) { <span class="risk-marker" [style.left.%]="v.value * 100" aria-hidden="true"></span><strong class="risk-value" [style.left]="'clamp(2.5rem, '+ (v.value * 100) +'%, calc(100% - 2.5rem))'">{{ v.value * 100 | number:'1.1-2' }} %</strong> }</div>
<div class="risk-labels"><span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span></div>
</div>
}
} @empty {
@for (label of ['Riesgo inmediato', 'Riesgo a 5 años']; track label) {
<div class="risk-scale"><p><strong>{{ label }}</strong> · No disponible</p><div class="risk-plot unavailable"><div class="risk-line" aria-hidden="true"></div></div><div class="risk-labels"><span>0 %</span><span>25 %</span><span>50 %</span><span>75 %</span><span>100 %</span></div></div>
}
<p class="muted">Ningún modelo vigente la ha evaluado.</p>
}
} @else if (models().length) {
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
+13 -2
View File
@@ -18,12 +18,12 @@
.cards { .cards {
display: grid; display: grid;
gap: var(--space-4); gap: var(--space-4);
grid-template-columns: 1fr; grid-template-columns: minmax(0, 1fr);
} }
@media (min-width: 1100px) { @media (min-width: 1100px) {
.cards { .cards {
grid-template-columns: repeat(2, 1fr); grid-template-columns: repeat(2, minmax(0, 1fr));
} }
.wide { .wide {
grid-column: 1 / -1; grid-column: 1 / -1;
@@ -33,3 +33,14 @@
mat-card-content { mat-card-content {
overflow-x: auto; overflow-x: auto;
} }
:host .risk-scale { max-width: 740px; margin: 8px 0 14px; }
:host .risk-scale p { margin: 0; }
:host .risk-plot { position: relative; padding-top: 24px; }
:host .risk-line { height: 16px; background: linear-gradient(to right, #42a77e 0 25%, #a8c243 25% 50%, #df8640 50% 75%, #c24269 75% 100%); }
:host .unavailable .risk-line { background: repeating-linear-gradient(to right, #d9dfe2 0, #d9dfe2 calc(25% - 1px), #fff calc(25% - 1px), #fff 25%); }
:host .risk-marker { position: absolute; bottom: -2px; width: 3px; height: 20px; background: #17324d; transform: translateX(-50%); }
:host .risk-value { position: absolute; top: 1px; transform: translateX(-50%); white-space: nowrap; color: #17324d; font-size: 13px; }
:host .risk-labels { display: flex; justify-content: space-between; font-size: 12px; margin-top: 3px; }
.export-actions { display: flex; justify-content: flex-end; margin-bottom: 12px; }
:host .cards, :host .wide { min-width: 0; }
+82 -5
View File
@@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import type { import type {
Condition, Condition,
DiagnosticReport, DiagnosticReport,
@@ -13,9 +14,14 @@ import type {
RiskAssessment, RiskAssessment,
} from 'fhir/r4'; } from 'fhir/r4';
import { code, ext, Fhir, label, resources } from '../fhir'; import { code, ext, Fhir, label, resources } from '../fhir';
import { CURP } from '../indicadores/follow-up'; import { CURP, exactAge, patientLabel, patientName } from '../indicadores/follow-up';
import { name } from '../indicadores/measures'; import { name } from '../indicadores/measures';
import { Figure, PALETTE, Plot } from '../plot'; import { Figure, PALETTE, Plot } from '../plot';
import { horizonRisk } from './risk-scale';
import { daysBetween, routeFacts, stages, Stages } from './stages';
import { HttpClient } from '@angular/common/http';
import { downloadDocument } from '../export-document';
import { firstValueFrom } from 'rxjs';
/** An Observation's value as the screens say it, whatever its type. */ /** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string { function shown(o: Observation): string {
@@ -30,12 +36,19 @@ function shown(o: Observation): string {
* champion models' risks with their curves. Everything read from the FHIR API. */ * champion models' risks with their curves. Everything read from the FHIR API. */
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot], imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot, Stages],
templateUrl: './paciente.html', templateUrl: './paciente.html',
styleUrl: './paciente.scss', styleUrl: './paciente.scss',
}) })
export class Paciente { export class Paciente {
private readonly route = inject(ActivatedRoute);
protected readonly exactAge = exactAge;
protected readonly cutoff = this.route.snapshot.queryParamMap.get('corte') ?? undefined;
protected readonly sample = this.route.snapshot.queryParamMap.get('muestra') ?? undefined;
private readonly fhir = inject(Fhir); private readonly fhir = inject(Fhir);
private readonly http = inject(HttpClient);
protected readonly exporting = signal(false);
protected readonly exportError = signal('');
readonly domain = input.required<string>(); readonly domain = input.required<string>();
readonly id = input.required<string>(); readonly id = input.required<string>();
@@ -44,10 +57,16 @@ export class Paciente {
loader: async ({ params: { domain, id } }) => { loader: async ({ params: { domain, id } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 }; const subject = { subject: `Patient/${id}`, _count: 200 };
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([ const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
this.fhir.read<Patient>(domain, 'Patient', id), domain === 'cacu' && this.cutoff
? this.fhir.search(domain, 'Patient', {_id:id, 'follow-up-cutoff':this.cutoff}).then(bundle => {
const patient = resources<Patient>(bundle, 'Patient', 'match')[0];
if (!patient) throw new Error('Paciente no encontrada');
return patient;
})
: this.fhir.read<Patient>(domain, 'Patient', id),
this.fhir.all(domain, 'Condition', subject), this.fhir.all(domain, 'Condition', subject),
this.fhir.all(domain, 'Procedure', subject), this.fhir.all(domain, 'Procedure', subject),
this.fhir.all(domain, 'DiagnosticReport', subject), this.fhir.all(domain, 'DiagnosticReport', { ...subject, 'stage-cutoff': domain === 'cacu' ? this.cutoff : undefined }),
this.fhir.all(domain, 'Observation', subject), this.fhir.all(domain, 'Observation', subject),
this.fhir.all(domain, 'RiskAssessment', subject), this.fhir.all(domain, 'RiskAssessment', subject),
]); ]);
@@ -64,6 +83,53 @@ export class Paciente {
}, },
}); });
protected readonly patient = computed(() => this.data.value()?.patient); protected readonly patient = computed(() => this.data.value()?.patient);
protected readonly sampleReportDate = computed(() => {
const d = this.data.value();
const report = d?.reports.find(r => code(r.code) === 'cervical_cytology' && r.effectiveDateTime === this.sample);
const hasResult = (report?.result ?? []).some(ref => {
const observation = d?.observations.get(ref.reference?.split('/')[1] ?? '');
return code(observation?.code) === 'cervical_cytology.result' && !!code(observation?.valueCodeableConcept);
});
return hasResult ? ext(report, 'report-date')?.valueDate : undefined;
});
protected readonly sampleFacts = computed(() => routeFacts(this.data.value()?.reports.find(r => code(r.code) === 'cervical_cytology' && r.effectiveDateTime === this.sample)));
protected async exportPatient(): Promise<void> {
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 timeline = stages(this.sample, this.sampleReportDate(), this.cutoff, this.sampleFacts());
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(exactAge(patient.birthDate,this.cutoff) ?? 'No disponible')],
['Estatus', this.status() || 'No disponible'],
...timeline.map((s,i) => ['Etapa', `${s.label}: ${s.state}${s.provenance ? ' · '+s.provenance : ''}; fecha ${s.date ?? '—'}; desde anterior ${daysBetween(i ? timeline[i-1].date : undefined,s.date) ?? '—'} días; desde toma ${daysBetween(timeline[0].date,s.date) ?? '—'} días`]),
...this.history().map(h => ['Historial', `${h.date} · ${h.kind} · ${h.text}${h.code ? ' ('+h.code+')' : ''}`]),
...this.tests().map(t => ['Pruebas', `${t.date} · ${t.kind} · ${t.reported ?? 'Pendiente'} · ${t.results.join(' · ') || '—'}`]),
];
const lastStage = timeline.map(s => s.date).filter((d): d is string => !!d).sort().at(-1);
if (lastStage) entries.splice(7 + timeline.length, 0, ['Etapas', `Tiempo transcurrido desde el último evento mostrado: ${daysBetween(lastStage,this.cutoff) ?? '—'} días (incluye asociaciones inferidas)`]);
const risk = this.riskScales();
if (!risk.length) entries.push(['Riesgo', 'Inmediato: No disponible · 5 años: No disponible']);
for (const r of risk) for (const [label, value] of [['Inmediato',r.immediate],['5 años',r.five]] as const)
entries.push(['Riesgo', `${r.outcome} · ${r.model} · ${label}: ${value ? (value.value*100).toFixed(2)+' %' : 'No disponible'}${value?.low !== undefined && value.high !== undefined ? ' · IC 95 % '+(value.low*100).toFixed(2)+'–'+(value.high*100).toFixed(2)+' %' : ''}`]);
const pct2 = (n: number) => (n*100).toFixed(2)+' %';
const scale = (r: (typeof risk)[number], label: string, v: (typeof risk)[number]['immediate']) => ({label:`${r.outcome} · ${r.model} · ${label}: ${v ? pct2(v.value) : 'No disponible'}`, outcome:r.outcome, model:r.model, horizon:label,
...(v ? {value:v.value, ...(v.low !== undefined && v.high !== undefined ? {low:v.low, high:v.high} : {})} : {})});
const scales = risk.length ? risk.flatMap(r => [scale(r,'Inmediato',r.immediate), scale(r,'5 años',r.five)]) : [{label:'Riesgo inmediato: No disponible'}, {label:'Riesgo a 5 años: No disponible'}];
const interval = (d?: number, inferred?: boolean) => d === undefined ? '—' : `${d} días${inferred ? ' (inferido)' : ''}`;
const isInferred = (x?: {provenance?: string}) => x?.provenance === 'Inferida temporalmente';
const route = timeline.map((s,i) => ({state:s.state, label:s.label, ...(s.provenance ? {provenance:s.provenance} : {}), ...(s.date ? {date:s.date} : {}),
prev: interval(daysBetween(i ? timeline[i-1].date : undefined, s.date), isInferred(s) || (i > 0 && isInferred(timeline[i-1]))),
start: interval(daysBetween(timeline[0].date, s.date), isInferred(s))}));
await downloadDocument(this.http,'pdf',{title:'Ficha individual',parameters:[['Corte (edad, estatus y etapas)',this.cutoff ?? 'No disponible'],['Historial y riesgos','Información longitudinal disponible; no filtrada por corte histórico']],columns:['Sección','Información'],rows:entries,timeline:route,risk_scales:scales});
} 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 error = computed(() => this.data.error()); protected readonly error = computed(() => this.data.error());
protected readonly loading = computed(() => this.data.isLoading()); protected readonly loading = computed(() => this.data.isLoading());
protected readonly history = computed(() => { protected readonly history = computed(() => {
@@ -123,6 +189,17 @@ export class Paciente {
})), })),
})); }));
}); });
protected readonly riskScales = computed(() => {
const latest = new Map<string, RiskAssessment>();
for (const risk of this.data.value()?.risks ?? []) {
const key = code(risk.method) ?? '';
if (!key.startsWith('cacu.cin2') && !key.startsWith('cacu.cancer')) continue;
if (!latest.has(key) || (latest.get(key)!.occurrenceDateTime ?? '') < (risk.occurrenceDateTime ?? '')) latest.set(key, risk);
}
return [...latest.entries()].map(([model, risk]) => ({model, index: risk.occurrenceDateTime,
outcome: model.startsWith('cacu.cin2') ? 'CIN2+' : 'Cáncer',
immediate: horizonRisk(risk, 0), five: horizonRisk(risk, 5)}));
});
protected readonly shown = signal<string | undefined>(undefined); protected readonly shown = signal<string | undefined>(undefined);
protected readonly curve = computed<Figure>(() => { protected readonly curve = computed<Figure>(() => {
const models = this.models().filter((m) => m.predictions.length > 1); const models = this.models().filter((m) => m.predictions.length > 1);
@@ -176,7 +253,7 @@ export class Paciente {
protected readonly identity = computed(() => { protected readonly identity = computed(() => {
const p = this.patient(); const p = this.patient();
return { return {
name: p?.name?.[0]?.text, name: patientName(p),
curp: p?.identifier?.find((i) => i.system === CURP)?.value, curp: p?.identifier?.find((i) => i.system === CURP)?.value,
numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value), numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value),
}; };
+14
View File
@@ -0,0 +1,14 @@
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};
}
+29
View File
@@ -0,0 +1,29 @@
import '@angular/compiler';
import { describe, expect, it } from 'vitest';
import type { RiskAssessment } from 'fhir/r4';
import { stages, daysBetween } 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('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();
});
});
+44
View File
@@ -0,0 +1,44 @@
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<string, StageFact>;
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;
}
@Component({selector:'app-stages', template: `
<div class="stage-line" [class.detailed]="detail()" [attr.aria-label]="summary()">
@for (s of items(); track s.label; let i = $index) {
<div class="stage"><span class="node" [class.registered]="s.state === 'Registrada'" [class.inferred]="s.provenance === 'Inferida temporalmente'" [class.pending]="s.state === 'Pendiente'" [class.ambiguous]="s.state === 'Ambigua'" [attr.title]="s.label + ': ' + s.state + (s.provenance ? ' · ' + s.provenance : '')"></span>
@if (detail()) { <div class="stage-detail"><strong>{{ s.label }}</strong><span>{{ s.state }}{{ s.provenance ? ' · ' + s.provenance : '' }}</span><span>{{ s.date ?? 'Sin fecha' }}</span><span class="interval">Desde anterior: {{ days(i ? items()[i-1].date : undefined, s.date) ?? '—' }}{{ i && days(items()[i-1].date, s.date) !== undefined && (s.provenance === 'Inferida temporalmente' || items()[i-1].provenance === 'Inferida temporalmente') ? ' días (inferido)' : (days(i ? items()[i-1].date : undefined, s.date) !== undefined ? ' días' : '') }}</span><span class="interval">Desde toma: {{ days(items()[0].date, s.date) ?? '—' }}{{ days(items()[0].date, s.date) !== undefined && s.provenance === 'Inferida temporalmente' ? ' días (inferido)' : (days(items()[0].date, s.date) !== undefined ? ' días' : '') }}</span></div> }
</div>
}
</div>
`, styles: `: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}.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}.stage:last-child{flex-basis:18px}.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){.detailed{display:block}.detailed .stage{display:flex;gap:12px;padding-bottom:10px}.detailed .stage::after{top:18px;left:9px;bottom:0;right:auto;border-top:0;border-left:1px solid #667b8a}.detailed .node{margin:0}.detailed .stage{text-align:left}.stage-detail{padding:0}.node{flex:none}}`})
export class Stages {
readonly sample = input<string>(); readonly report = input<string>(); readonly cutoff = input<string>(); readonly detail = input(false);
readonly facts = input<StageFacts>({});
protected readonly items = computed(() => stages(this.sample(),this.report(),this.cutoff(),this.facts()));
protected readonly summary = computed(() => this.items().map(x=>x.label+': '+x.state+(x.provenance?' · '+x.provenance:'')).join('; '));
protected readonly lastDate = computed(() => this.items().map(x=>x.date).filter((x):x is string=>!!x).sort().at(-1));
protected readonly days = daysBetween;
}