diff --git a/src/app/export-document.ts b/src/app/export-document.ts
new file mode 100644
index 0000000..20c8e4d
--- /dev/null
+++ b/src/app/export-document.ts
@@ -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);
+}
diff --git a/src/app/indicadores/follow-up.spec.ts b/src/app/indicadores/follow-up.spec.ts
index 8eceef2..5546bed 100644
--- a/src/app/indicadores/follow-up.spec.ts
+++ b/src/app/indicadores/follow-up.spec.ts
@@ -1,8 +1,32 @@
-import type { RiskAssessment } from 'fhir/r4';
-import { ageGroup, currentRisk, windowStart } from './follow-up';
+import '@angular/compiler';
+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';
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)', () => {
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
diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts
index c389271..44c708a 100644
--- a/src/app/indicadores/follow-up.ts
+++ b/src/app/indicadores/follow-up.ts
@@ -1,5 +1,6 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
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. */
export interface Row {
@@ -8,7 +9,9 @@ export interface Row {
curp?: string;
status: 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 };
daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string };
@@ -17,6 +20,36 @@ export interface Row {
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][] = [
[25, 34],
[35, 44],
@@ -49,7 +82,7 @@ export function currentRisk(
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) =>
(r.prediction ?? [])
- .filter((p) => p.whenRange?.high?.value === horizon)
+ .filter((p) => p.whenRange?.high?.value === horizon && p.probabilityDecimal !== undefined)
.map((p) => ({ r, p })),
);
if (!mine.length) return undefined;
@@ -60,7 +93,7 @@ export function currentRisk(
return Math.max(
...mine
.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}`);
return {
patient,
- name: patient.name?.[0]?.text,
+ name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
+ age: exactAge(patient.birthDate, cutoff),
+ stageFacts: routeFacts(last),
cytology: last && {
date: last.effectiveDateTime!,
+ reportDate: ext(last, 'report-date')?.valueDate,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
},
@@ -186,7 +222,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
.at(-1);
return {
patient,
- name: patient.name?.[0]?.text,
+ name: patientName(patient),
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
diff --git a/src/app/indicadores/tab-riesgos.html b/src/app/indicadores/tab-riesgos.html
index 6caf560..8d7fe0e 100644
--- a/src/app/indicadores/tab-riesgos.html
+++ b/src/app/indicadores/tab-riesgos.html
@@ -1,4 +1,12 @@
+
+@if (exportMessage()) { {{ exportMessage() }}
}
+@if (invalidAge()) { Indique edades enteras entre 0 y 150; la mínima no puede superar la máxima. El rango no está aplicado.
}
+@if (!globalFilters() && !capabilities.isLoading()) { El servidor no declara búsqueda global ni filtros de edad.
}
@if (error()) {
No se pudo leer la lista de seguimiento.
@@ -61,12 +71,13 @@
| Paciente |
- Grupo de edad |
+ Edad |
Estatus |
+ Etapas |
Última citología |
VPH |
Biopsia |
- Riesgo LIEAG+ ({{ horizon() }} a) |
+ Riesgo CIN2+ ({{ horizon() }} a) |
Riesgo cáncer ({{ horizon() }} a) |
Días toma → diagnóstico |
@@ -75,15 +86,16 @@
@for (row of rows(); track row.patient.id) {
|
- {{
- row.name ?? row.patient.id!.slice(0, 10)
+ {{
+ patientLabel(row.patient)
}}
@if (row.curp) {
{{ row.curp }}
}
|
- {{ row.ageGroup }} |
+ {{ row.age ?? 'No disponible' }} |
{{ name(row.status) }} |
+ |
@if (row.cytology; as c) {
{{ c.date }} ·
@@ -122,9 +134,10 @@
|
{{ row.daysToDiagnosis ?? '—' }} |
+ @if (expanded() === row.patient.id) { |
}
} @empty {
- |
+ |
{{ page() ? 'Nadie en la lista con estos filtros.' : 'Cargando…' }}
|
diff --git a/src/app/indicadores/tab-riesgos.scss b/src/app/indicadores/tab-riesgos.scss
index 1c5bc31..3f04c08 100644
--- a/src/app/indicadores/tab-riesgos.scss
+++ b/src/app/indicadores/tab-riesgos.scss
@@ -40,3 +40,8 @@ a {
.pager .muted {
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); }
diff --git a/src/app/indicadores/tab-riesgos.ts b/src/app/indicadores/tab-riesgos.ts
index 508dd23..21f43fb 100644
--- a/src/app/indicadores/tab-riesgos.ts
+++ b/src/app/indicadores/tab-riesgos.ts
@@ -8,8 +8,13 @@ import { MatSelectModule } from '@angular/material/select';
import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir';
-import { rows, windowStart } from './follow-up';
+import { patientLabel, rows, windowStart } from './follow-up';
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'];
@@ -25,12 +30,16 @@ const STATUSES = ['case', 'pre_colposcopy', 'post_colposcopy', 'post_treatment']
MatInputModule,
MatSelectModule,
RouterLink,
+ Stages,
],
templateUrl: './tab-riesgos.html',
styleUrl: './tab-riesgos.scss',
})
export class TabRiesgos {
private readonly fhir = inject(Fhir);
+ private readonly http = inject(HttpClient);
+ protected readonly exporting = signal(false);
+ protected readonly exportMessage = signal('');
readonly domain = input.required();
protected readonly cutoff = signal('');
@@ -39,11 +48,29 @@ export class TabRiesgos {
protected readonly horizon = signal(5);
protected readonly sort = signal('-recent');
protected readonly size = signal(20);
+ protected readonly ageMin = signal(null);
+ protected readonly ageMax = signal(null);
+ protected readonly search = signal('');
+ protected readonly expanded = signal(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,
+ });
+ 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((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. */
private readonly moved = signal(undefined);
protected readonly statuses = STATUSES;
protected readonly name = name;
+ protected readonly patientLabel = patientLabel;
private readonly first = resource({
params: () => ({
@@ -54,6 +81,9 @@ export class TabRiesgos {
'risk-horizon': this.horizon(),
_sort: this.sort(),
_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 } }) => {
this.moved.set(undefined);
@@ -65,6 +95,7 @@ export class TabRiesgos {
},
});
protected readonly loading = signal(false);
+ protected readonly queryLoading = computed(() => this.first.isLoading());
protected readonly page = computed(() => this.moved() ?? this.first.value());
/** The cut-off as applied (the server's default when none is given). */
protected readonly applied = computed(() => {
@@ -84,6 +115,40 @@ export class TabRiesgos {
});
protected readonly error = computed(() => this.first.error());
+ protected async exportList(format: 'xlsx' | 'pdf'): Promise {
+ 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 = {'-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 {
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);
if (!next) return;
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 {
- 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 {
this.loading.set(false);
}
diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html
index 904dfd1..dd8e530 100644
--- a/src/app/paciente/paciente.html
+++ b/src/app/paciente/paciente.html
@@ -1,4 +1,6 @@
+ @if (domain() === 'cacu' && patient()) { }
+ @if (exportError()) { {{ exportError() }}
}
arrow_back Regresar
@@ -6,7 +8,8 @@
No se encontró la paciente.
} @else if (patient(); as p) {
- {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }}
+ {{ identity().name ?? p.id?.slice(0, 10) ?? 'No disponible' }} @if (identity().name && p.id) { {{ p.id.slice(0, 10) }} }
+ @if (domain() === 'cacu') { · Edad: {{ exactAge(p.birthDate, cutoff) ?? 'No disponible' }} }
@@ -43,6 +46,7 @@
Historial médico
+ @if (domain() === 'cacu') { }
@@ -108,7 +112,24 @@
>Riesgos y recomendaciones
- @if (models().length) {
+ @if (domain() === 'cacu') {
+ Divisiones numéricas descriptivas; no representan umbrales clínicos.
+ @for (model of riskScales(); track model.model) {
+ {{ model.outcome }} · {{ model.model }} · fecha índice {{ model.index }}
+ @for (scale of [{label: 'Riesgo inmediato (al índice)', value: model.immediate}, {label: 'Riesgo a 5 años', value: model.five}]; track scale.label) {
+
+
{{ scale.label }} @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 }
+
@if (scale.value; as v) {
{{ v.value * 100 | number:'1.1-2' }} % }
+
0 %25 %50 %75 %100 %
+
+ }
+ } @empty {
+ @for (label of ['Riesgo inmediato', 'Riesgo a 5 años']; track label) {
+ {{ label }} · No disponible
0 %25 %50 %75 %100 %
+ }
+ Ningún modelo vigente la ha evaluado.
+ }
+ } @else if (models().length) {
diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss
index ab298fc..2077612 100644
--- a/src/app/paciente/paciente.scss
+++ b/src/app/paciente/paciente.scss
@@ -18,12 +18,12 @@
.cards {
display: grid;
gap: var(--space-4);
- grid-template-columns: 1fr;
+ grid-template-columns: minmax(0, 1fr);
}
@media (min-width: 1100px) {
.cards {
- grid-template-columns: repeat(2, 1fr);
+ grid-template-columns: repeat(2, minmax(0, 1fr));
}
.wide {
grid-column: 1 / -1;
@@ -33,3 +33,14 @@
mat-card-content {
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; }
diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts
index 65688e6..715797c 100644
--- a/src/app/paciente/paciente.ts
+++ b/src/app/paciente/paciente.ts
@@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { RouterLink } from '@angular/router';
+import { ActivatedRoute } from '@angular/router';
import type {
Condition,
DiagnosticReport,
@@ -13,9 +14,14 @@ import type {
RiskAssessment,
} from 'fhir/r4';
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 { 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. */
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. */
@Component({
selector: 'app-paciente',
- imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot],
+ imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot, Stages],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
})
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 http = inject(HttpClient);
+ protected readonly exporting = signal(false);
+ protected readonly exportError = signal('');
readonly domain = input.required();
readonly id = input.required();
@@ -44,10 +57,16 @@ export class Paciente {
loader: async ({ params: { domain, id } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 };
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
- this.fhir.read(domain, 'Patient', id),
+ domain === 'cacu' && this.cutoff
+ ? this.fhir.search(domain, 'Patient', {_id:id, 'follow-up-cutoff':this.cutoff}).then(bundle => {
+ const patient = resources(bundle, 'Patient', 'match')[0];
+ if (!patient) throw new Error('Paciente no encontrada');
+ return patient;
+ })
+ : this.fhir.read(domain, 'Patient', id),
this.fhir.all(domain, 'Condition', 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, 'RiskAssessment', subject),
]);
@@ -64,6 +83,53 @@ export class Paciente {
},
});
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 {
+ 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 loading = computed(() => this.data.isLoading());
protected readonly history = computed(() => {
@@ -123,6 +189,17 @@ export class Paciente {
})),
}));
});
+ protected readonly riskScales = computed(() => {
+ const latest = new Map();
+ 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(undefined);
protected readonly curve = computed(() => {
const models = this.models().filter((m) => m.predictions.length > 1);
@@ -176,7 +253,7 @@ export class Paciente {
protected readonly identity = computed(() => {
const p = this.patient();
return {
- name: p?.name?.[0]?.text,
+ name: patientName(p),
curp: p?.identifier?.find((i) => i.system === CURP)?.value,
numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value),
};
diff --git a/src/app/paciente/risk-scale.ts b/src/app/paciente/risk-scale.ts
new file mode 100644
index 0000000..c2fd813
--- /dev/null
+++ b/src/app/paciente/risk-scale.ts
@@ -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};
+}
diff --git a/src/app/paciente/stages-risk.spec.ts b/src/app/paciente/stages-risk.spec.ts
new file mode 100644
index 0000000..91efcd8
--- /dev/null
+++ b/src/app/paciente/stages-risk.spec.ts
@@ -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();
+ });
+});
diff --git a/src/app/paciente/stages.ts b/src/app/paciente/stages.ts
new file mode 100644
index 0000000..c6f9848
--- /dev/null
+++ b/src/app/paciente/stages.ts
@@ -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;
+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: `
+
+ @for (s of items(); track s.label; let i = $index) {
+
+ @if (detail()) {
{{ s.label }}{{ s.state }}{{ s.provenance ? ' · ' + s.provenance : '' }}{{ s.date ?? 'Sin fecha' }}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' : '') }}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' : '') }}
}
+
+ }
+
+
+`, 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(); readonly report = input(); readonly cutoff = input(); readonly detail = input(false);
+ readonly facts = input({});
+ 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;
+}