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
+69 -2
View File
@@ -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<string>();
protected readonly cutoff = signal<string>('');
@@ -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<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. */
private readonly moved = signal<Bundle | undefined>(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<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 {
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);
}