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
+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);
}
+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 ?? '',
+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;
}