import { DecimalPipe } from '@angular/common'; import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { RouterLink } from '@angular/router'; import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; 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']; /** CaCu's follow-up list at a cut-off: who had a cytology in the window, her status, * results and current risks, in the order asked for. */ @Component({ selector: 'app-tab-riesgos', imports: [ DecimalPipe, FormsModule, MatButtonModule, MatFormFieldModule, 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(''); protected readonly window = signal(3); protected readonly status = signal(''); 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: () => ({ domain: this.domain(), 'follow-up-window': this.window(), 'follow-up-cutoff': this.cutoff() || undefined, 'follow-up-status': this.status() || undefined, '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); return this.fhir.search(domain, 'Patient', { ...params, _revinclude: ['DiagnosticReport:subject', 'RiskAssessment:subject'], '_include:iterate': 'DiagnosticReport:result', }); }, }); 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(() => { const self = this.page()?.link?.find((l) => l.relation === 'self')?.url; return self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : ''; }); protected readonly offset = computed(() => { const self = this.page()?.link?.find((l) => l.relation === 'self')?.url; return self ? Number(new URL(self).searchParams.get('_offset') ?? 0) : 0; }); protected readonly rows = computed(() => { const page = this.page(); const cutoff = this.applied(); return page && cutoff ? rows(page, windowStart(cutoff, this.window()), cutoff, this.horizon()) : []; }); 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); } protected async go(relation: 'next' | 'previous'): Promise { const page = this.page(); 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 { 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); } } }