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.
This commit is contained in:
Angel Capetillo Zavala
2026-11-27 18:42:42 -06:00
parent 31400c77b1
commit c0e4920159
12 changed files with 386 additions and 25 deletions
+23 -2
View File
@@ -1,4 +1,6 @@
<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()]"
><mat-icon>arrow_back</mat-icon> Regresar</a
>
@@ -6,7 +8,8 @@
<p class="muted" role="alert">No se encontró la paciente.</p>
} @else if (patient(); as p) {
<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>
<dl class="summary">
<div>
@@ -43,6 +46,7 @@
<mat-card appearance="outlined">
<mat-card-header><mat-card-title>Historial médico</mat-card-title></mat-card-header>
<mat-card-content>
@if (domain() === 'cacu') { <app-stages [sample]="sample" [report]="sampleReportDate()" [cutoff]="cutoff" [facts]="sampleFacts()" [detail]="true" /> }
<table class="plain">
<thead>
<tr>
@@ -108,7 +112,24 @@
><mat-card-title>Riesgos y recomendaciones</mat-card-title></mat-card-header
>
<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">
<thead>
<tr>
+13 -2
View File
@@ -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; }
+82 -5
View File
@@ -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<string>();
readonly id = input.required<string>();
@@ -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<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, '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<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 loading = computed(() => this.data.isLoading());
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 curve = computed<Figure>(() => {
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),
};
+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;
}