import { DecimalPipe } from '@angular/common'; import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatSelectModule } from '@angular/material/select'; import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { RouterLink } from '@angular/router'; import type { Condition, DiagnosticReport, Observation, Patient, Procedure, RiskAssessment, } from 'fhir/r4'; import { Api } from '../api/api'; import { curve } from '../api/fn/models/curve'; import { readReport$Json } from '../api/fn/models/read-report-json'; import type { Domain } from '../api/models/domain'; import { code, EXT, ext, Fhir, label, resources } from '../fhir'; import { scenarioFigure } from '../gobernanza/figures'; import { ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { Figure, PALETTE, Plot } from '../plot'; import { Loading } from '../loading'; import { Factores, ScenarioFactors } from './factores'; import { identityRows, loadTeaPatient, Study } from './tea-data'; import { ageNorm, Centile } from './tea-figures'; import { TeaSection } from './tea-section'; import { exportTeaPdf, forestTitle, probabilityTitle, recordSections, riskSections, Section, } from './tea-sections'; /** An Observation's value as the screens say it, whatever its type. */ function shown(o: Observation): string { if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo'; if (o.valueCodeableConcept) { // The screens' own name for the code (BI-RADS 4C), else the server's display. const c = code(o.valueCodeableConcept) ?? ''; return (c in LABELS ? name(c) : '') || label(o.valueCodeableConcept); } if (o.valueQuantity) return `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim(); return o.valueString ?? o.valueDateTime ?? ''; } /** One patient: her history (conditions, procedures), her tests and results, and the * champion models' risks with their curves. Everything read from the FHIR API. */ @Component({ selector: 'app-paciente', imports: [ Factores, Loading, DecimalPipe, MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatSelectModule, MatSlideToggleModule, RouterLink, Plot, TeaSection, ], templateUrl: './paciente.html', styleUrl: './paciente.scss', }) export class Paciente { private readonly fhir = inject(Fhir); private readonly api = inject(Api); private readonly host = inject>(ElementRef); readonly domain = input.required(); readonly id = input.required(); /** The follow-up list she was opened from: its window (months) and cut-off. */ readonly ventana = input(); readonly corte = input(); readonly risk = input(false); private readonly data = resource({ params: () => (this.domain() === 'tea' ? undefined : { domain: this.domain(), id: this.id() }), 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), this.fhir.all(domain, 'Condition', subject), this.fhir.all(domain, 'Procedure', subject), this.fhir.all(domain, 'DiagnosticReport', subject), this.fhir.all(domain, 'Observation', subject), this.fhir.all(domain, 'RiskAssessment', subject), ]); return { patient, conditions: resources(conditions, 'Condition'), procedures: resources(procedures, 'Procedure'), reports: resources(reports, 'DiagnosticReport').reverse(), observations: new Map( resources(observations, 'Observation').map((o) => [o.id, o]), ), risks: resources(risks, 'RiskAssessment'), }; }, }); protected readonly patient = computed(() => this.data.value()?.patient); protected readonly error = computed(() => this.data.error()); protected readonly loading = computed(() => this.data.isLoading()); protected readonly history = computed(() => { const d = this.data.value(); if (!d) return []; return [ ...d.conditions.map((c) => ({ date: c.recordedDate ?? '', kind: 'Diagnóstico', text: label(c.code), // the ICD-10 code a note diagnosed by (the platform's own codes stay unsaid) code: c.code?.coding?.find((x) => x.system?.includes('icd-10'))?.code, })), ...d.procedures.map((p) => ({ date: p.performedDateTime ?? '', kind: 'Procedimiento', text: label(p.code), code: undefined, })), ].sort((a, b) => b.date.localeCompare(a.date)); }); protected readonly tests = computed(() => { const d = this.data.value(); if (!d) return []; return d.reports.map((r) => { const results = (r.result ?? []) .map((x) => d.observations.get(x.reference?.split('/')[1])) .filter((o) => !!o) as Observation[]; return { date: r.effectiveDateTime ?? '', reported: ext(r, 'report-date')?.valueDate, kind: label(r.code), status: r.status, // "BI-RADS 4C", not "BI-RADS: BI-RADS 4C" results: results.map((o) => { const [name, value] = [label(o.code), shown(o)]; return value.startsWith(name) ? value : `${name}: ${value}`; }), }; }); }); /** One model's latest risk assessment per model. */ protected readonly models = computed(() => { const latest = new Map(); for (const r of this.data.value()?.risks ?? []) { const key = code(r.method) ?? ''; if ( !latest.has(key) || (latest.get(key)!.occurrenceDateTime ?? '') < (r.occurrenceDateTime ?? '') ) latest.set(key, r); } return [...latest.values()].map((r) => ({ model: code(r.method) ?? '', text: r.method?.text ?? '', version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), index: r.occurrenceDateTime ?? '', // the clinical scenarios of the model's report she falls in scenarios: (r.extension ?? []) .filter((e) => e.url === EXT + 'escenario-clinico') .map((e) => e.valueString ?? ''), predictions: (r.prediction ?? []).map((p) => ({ years: p.whenRange?.high?.value ?? 0, p: p.probabilityDecimal ?? 0, low: ext(p, 'ic-bajo')?.valueDecimal, high: ext(p, 'ic-alto')?.valueDecimal, })), })); }); /** "Análisis de supervivencia" and "Análisis de recurrencia": the curves of her clinical * scenarios, from the report of the model version that scored her. */ protected readonly survival = this.analysis('survival'); protected readonly recurrence = this.analysis('recurrence'); protected readonly recurrenceModel = computed(() => this.models().find((m) => m.model.endsWith('.recurrence') && m.version), ); private analysis(name: 'survival' | 'recurrence') { return resource({ params: () => { const m = this.models().find( (x) => x.model === `${this.domain()}.${name}` && x.scenarios.length && x.version, ); return m ? { m, domain: this.domain() } : undefined; }, loader: async ({ params: { m, domain } }) => { const report = await this.api.invoke(readReport$Json, { domain: domain as Domain, name, version: m.version, report: 'interpretability', }); const mine = (all: any[]) => all.filter((e) => m.scenarios.includes(e.escenario)); if (name === 'recurrence') { const r = (report?.['recurrencia'] ?? {}) as any; // The risk factors of her scenarios, by horizon (the development tables). const technical = (await this.api.invoke(readReport$Json, { domain: domain as Domain, name, version: m.version, report: 'technical_validation', })) as any; const summary = technical?.['recurrencia_desarrollo']?.['tablas']?.['escenarios_resumen']; return { factors: mine(summary?.['filas'] ?? []) as ScenarioFactors[], scenarios: m.scenarios, figures: mine(r['escenarios'] ?? []).map((e) => scenarioFigure( `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, recaídas = ${e.recaidas.toLocaleString('es-MX')})`, e, r['horizons_months'], 'Supervivencia libre de recaída', ), ), }; } return { factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[], scenarios: m.scenarios, figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) => scenarioFigure( `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, e, e.horizons_months, 'Supervivencia S(t)', ), ), }; }, }); } protected readonly curve = computed
(() => { const models = this.models().filter((m) => m.predictions.length > 1); return { data: models.flatMap((m, i) => { const x = m.predictions.map((p) => p.years); const color = PALETTE[i % PALETTE.length]; return [ { x, y: m.predictions.map((p) => (p.high ?? p.p) * 100), mode: 'lines', line: { width: 0 }, showlegend: false, hoverinfo: 'skip', }, { x, y: m.predictions.map((p) => (p.low ?? p.p) * 100), mode: 'lines', line: { width: 0 }, fill: 'tonexty', fillcolor: color + '33', showlegend: false, hoverinfo: 'skip', }, { x, y: m.predictions.map((p) => p.p * 100), mode: 'lines+markers', name: m.text.replace(/ v\d+$/, ''), line: { color }, }, ]; }), layout: { xaxis: { title: { text: 'Años desde la fecha índice' }, dtick: 1 }, // At least 0–5 %: a near-zero risk reads as near zero, not as a full axis. yaxis: { title: { text: 'Probabilidad (%)' }, range: [0, Math.max(5, this.top() * 110)], tickformat: '.1f', }, }, }; }); private top(): number { return Math.max(0, ...this.models().flatMap((m) => m.predictions.map((p) => p.high ?? p.p))); } protected readonly name = name; protected readonly identity = computed(() => { const p = this.patient(); return { name: p?.name?.[0]?.text, curp: p?.identifier?.find((i) => i.system === CURP)?.value, // each record number once (several sources may carry the same one) numbers: [ ...new Set( (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''), ), ].filter(Boolean), }; }); /** CaMa: her row on the follow-up list (window and cut-off as opened, else the widest * window up to the last day with data), as the list shows it: the old record's card. */ private readonly listed = resource({ params: () => this.domain() === 'cama' ? { domain: this.domain(), id: this.id(), window: Number(this.ventana()) || 12, cutoff: this.corte() || undefined, } : undefined, loader: async ({ params: { domain, id, window, cutoff } }) => { const page = await this.fhir.search(domain, 'Patient', { _id: id, 'follow-up-window': window, 'follow-up-cutoff': cutoff, _revinclude: ['DiagnosticReport:subject'], '_include:iterate': 'DiagnosticReport:result', }); const self = page.link?.find((l) => l.relation === 'self')?.url; const applied = self ? (new URL(self).searchParams.get('follow-up-cutoff') ?? '') : ''; return { window, cutoff: applied, row: camaRows(page, applied)[0] }; }, }); protected readonly cama = computed(() => { const found = this.listed.value(); const d = this.data.value(); if (!found || !d) return undefined; // Her own latest mammogram and biopsy, on the list or not. const latest = (study: string) => d.reports .filter((r) => code(r.code) === study) .sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '')) .at(-1); const value = (r: DiagnosticReport | undefined, field: string) => { const o = (r?.result ?? []) .map((x) => d.observations.get(x.reference?.split('/')[1])) .find((x) => code(x?.code) === field); return o ? shown(o) : undefined; }; const mammogram = latest('mammography'); const biopsy = latest('breast_biopsy'); const treated = d.procedures.some((p) => (p.performedDateTime ?? '') <= found.cutoff); const r = found.row; return { ...found, ageGroup: r?.ageGroup ?? ageGroup(d.patient.birthDate, found.cutoff, CAMA_AGE_GROUPS), scenario: treated ? 'Post-tratamiento' : 'En observación', status: r ? name(r.status) : undefined, priority: r ? (PRIORITY[r.priority] ?? r.priority) : undefined, birads: value(mammogram, 'mammography.birads'), mammogram: mammogram?.effectiveDateTime?.slice(0, 10), days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined, histology: value(biopsy, 'breast_biopsy.histology'), biopsy: biopsy ? (ext(biopsy, 'report-date')?.valueDate ?? biopsy.effectiveDateTime) : undefined, }; }); protected readonly status = computed(() => { const p = this.patient(); return p ? name(ext(p, 'follow-up-status')?.valueCoding?.code ?? '') : ''; }); protected readonly tea = resource({ params: () => (this.domain() === 'tea' ? this.id() : undefined), loader: ({ params }) => loadTeaPatient(this.fhir, params), }); protected readonly norms = resource({ params: () => (this.risk() || !this.tea.hasValue() ? undefined : this.tea.value().studies), loader: ({ params }) => this.loadNorms(params), }); protected readonly onlyAltered = signal(false); protected readonly selectedKey = signal(''); protected readonly selectedPair = computed(() => { const pairs = this.tea.hasValue() ? this.tea.value().pairs : []; return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0]; }); protected readonly teaIdentity = computed(() => this.tea.hasValue() ? identityRows(this.tea.value().patient) : [], ); protected readonly teaSections = computed(() => { if (!this.tea.hasValue()) return []; const patient = this.tea.value(); return this.risk() ? riskSections(patient, this.onlyAltered(), this.selectedPair()) : recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map()); }); protected readonly forestTitle = forestTitle; protected readonly probabilityTitle = probabilityTitle; protected readonly exporting = signal(false); protected readonly exportError = signal(false); private async loadNorms(studies: Study[]) { const curves = new Map>(); const charts = await Promise.all( studies.flatMap((eeg) => eeg.metrics.map(async (metric) => { const model = /^tea\.([^/]+)\/([1-9]\d*)$/.exec(metric.model ?? ''); if ( !model || metric.key === 'paroxysmal_spikes' || metric.value == null || eeg.age == null ) { return undefined; } const [, name, version] = model; const key = model[0]; if (!curves.has(key)) { curves.set( key, this.api .invoke(curve, { domain: 'tea', name, version: Number(version) }) .then((rows) => rows as Centile[]) .catch(() => []), ); } const rows = await curves.get(key)!; if (!rows.some((row) => row.median != null)) return undefined; return [ `${eeg.id}|${metric.key}`, { title: 'Norma por edad · p5–p95', figure: ageNorm(rows, metric, eeg.age), }, ] as const; }), ), ); return new Map(charts.filter((chart) => chart !== undefined)); } protected async download(): Promise { this.exportError.set(false); this.exporting.set(true); try { await exportTeaPdf( this.risk() ? 'riesgos' : 'seguimiento', this.risk() ? 'Análisis de riesgo TEA' : 'Expediente TEA', this.teaSections(), this.host.nativeElement.querySelectorAll('app-plot .plot'), ); } catch { this.exportError.set(true); } finally { this.exporting.set(false); } } }