520 lines
20 KiB
TypeScript
520 lines
20 KiB
TypeScript
import { DecimalPipe } from '@angular/common';
|
||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||
import { MatButtonModule } from '@angular/material/button';
|
||
import { MatCardModule } from '@angular/material/card';
|
||
import { MatIconModule } from '@angular/material/icon';
|
||
import { RouterLink } from '@angular/router';
|
||
import type {
|
||
Condition,
|
||
DiagnosticReport,
|
||
Observation,
|
||
Patient,
|
||
Procedure,
|
||
RiskAssessment,
|
||
} from 'fhir/r4';
|
||
import { Api } from '../api/api';
|
||
import { studies as eegStudies } from '../api/fn/eeg/studies';
|
||
import { study as eegStudy } from '../api/fn/eeg/study';
|
||
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 { savePdf } from '../export';
|
||
import { recordSheets } from './record-sheets';
|
||
import { riskScales, RiskScales } from './risk-scales';
|
||
import { route, Stages } from './stages';
|
||
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
|
||
import { LABELS, name, PRIORITY } from '../indicadores/measures';
|
||
import {
|
||
BIOMARKER_NAMES,
|
||
byDeviation,
|
||
headMap,
|
||
METRIC_NAMES,
|
||
OUTCOME_NAMES,
|
||
ZONE_NAMES,
|
||
LEVEL_NAMES,
|
||
} from '../eeg-labels';
|
||
import type { Relation } from '../api/models/relation';
|
||
import { Figure, PALETTE, Plot } from '../plot';
|
||
import { Loading } from '../loading';
|
||
import { Factores, ScenarioFactors } from './factores';
|
||
|
||
/** 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,
|
||
MatIconModule,
|
||
RouterLink,
|
||
Plot,
|
||
RiskScales,
|
||
Stages,
|
||
],
|
||
templateUrl: './paciente.html',
|
||
styleUrl: './paciente.scss',
|
||
})
|
||
export class Paciente {
|
||
private readonly fhir = inject(Fhir);
|
||
private readonly api = inject(Api);
|
||
readonly domain = input.required<string>();
|
||
readonly id = input.required<string>();
|
||
/** The follow-up list she was opened from: its window (months) and cut-off. */
|
||
readonly ventana = input<string>();
|
||
readonly corte = input<string>();
|
||
/** CaCu: the day of the cytology the list showed of her. */
|
||
readonly citologia = input<string>();
|
||
|
||
private readonly data = resource({
|
||
params: () => ({ 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<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, 'Observation', subject),
|
||
this.fhir.all(domain, 'RiskAssessment', subject),
|
||
]);
|
||
return {
|
||
patient,
|
||
conditions: resources<Condition>(conditions, 'Condition'),
|
||
procedures: resources<Procedure>(procedures, 'Procedure'),
|
||
reports: resources<DiagnosticReport>(reports, 'DiagnosticReport').reverse(),
|
||
observations: new Map(
|
||
resources<Observation>(observations, 'Observation').map((o) => [o.id, o]),
|
||
),
|
||
risks: resources<RiskAssessment>(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));
|
||
});
|
||
private readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
|
||
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
|
||
/** CaCu: the route of the cytology she was opened at, else of her latest, by the cut-off. */
|
||
protected readonly stages = computed(() => {
|
||
const cytologies = (this.data.value()?.reports ?? []).filter(
|
||
(r) => code(r.code) === 'cervical_cytology',
|
||
);
|
||
const shown = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
|
||
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
|
||
});
|
||
protected readonly scales = computed(() =>
|
||
this.domain() === 'cacu' ? riskScales(this.models()) : [],
|
||
);
|
||
protected readonly saving = signal(false);
|
||
protected readonly saveError = signal('');
|
||
/** CaCu: her record as a PDF. */
|
||
protected async save(): Promise<void> {
|
||
this.saving.set(true);
|
||
this.saveError.set('');
|
||
try {
|
||
const { name: who, curp, numbers } = this.identity();
|
||
const facts: [string, string | undefined][] = [
|
||
['Nombre', who],
|
||
['CURP', curp],
|
||
['Expedientes', numbers.join(', ')],
|
||
['Fecha de nacimiento', this.patient()?.birthDate],
|
||
['Edad', this.age()?.toString()],
|
||
['Estatus de seguimiento', this.status()],
|
||
['Fecha de corte', this.cutoff()],
|
||
];
|
||
const sheets = recordSheets(
|
||
facts,
|
||
this.stages() ?? [],
|
||
this.history(),
|
||
this.tests(),
|
||
this.scales(),
|
||
);
|
||
await savePdf(sheets, 'expediente-cacu');
|
||
} catch {
|
||
this.saveError.set('No se generó el archivo.');
|
||
} finally {
|
||
this.saving.set(false);
|
||
}
|
||
}
|
||
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<string, RiskAssessment>();
|
||
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)',
|
||
),
|
||
),
|
||
};
|
||
},
|
||
});
|
||
}
|
||
/** TEA: her latest ADOS-2 (an encounter whose observations are the catalog's
|
||
* `ados2.*` fields), item by item, and its totals. */
|
||
protected readonly ados2 = computed(() => {
|
||
const d = this.data.value();
|
||
if (!d) return undefined;
|
||
const field = (o: Observation) => (code(o.code) ?? '').replace(/^ados2\./, '');
|
||
const scored = [...d.observations.values()].filter(
|
||
(o) => (code(o.code) ?? '').startsWith('ados2.') && o.valueQuantity?.value !== undefined,
|
||
);
|
||
const latest = scored
|
||
.map((o) => o.effectiveDateTime ?? '')
|
||
.sort()
|
||
.at(-1);
|
||
if (latest === undefined) return undefined;
|
||
const results = scored.filter((o) => (o.effectiveDateTime ?? '') === latest);
|
||
const totals = ['social_affect_total', 'restricted_repetitive_total', 'overall_total'];
|
||
const items = results.filter((o) => !totals.includes(field(o)));
|
||
const figure: Figure = {
|
||
data: [
|
||
{
|
||
type: 'bar',
|
||
orientation: 'h',
|
||
y: items.map((o) => label(o.code)),
|
||
x: items.map((o) => o.valueQuantity!.value!),
|
||
marker: { color: PALETTE[0] },
|
||
hovertemplate: '%{y}: %{x}<extra></extra>',
|
||
},
|
||
],
|
||
layout: {
|
||
showlegend: false,
|
||
margin: { t: 10, r: 16, b: 40, l: 16 },
|
||
xaxis: { title: { text: 'Puntaje (0 a 3)' }, range: [0, 3], dtick: 1 },
|
||
yaxis: { autorange: 'reversed', automargin: true, type: 'category' },
|
||
},
|
||
};
|
||
return {
|
||
date: latest.slice(0, 10),
|
||
figure,
|
||
height: 60 + items.length * 22,
|
||
totals: results
|
||
.filter((o) => totals.includes(field(o)))
|
||
.map((o) => ({ label: label(o.code), value: o.valueQuantity!.value! })),
|
||
};
|
||
});
|
||
|
||
/** TEA: her EEG as analysed (the latest), its quality and its metrics against the age
|
||
* curves: those outside the band are its alterations. */
|
||
protected readonly eeg = resource({
|
||
params: () => (this.domain() === 'tea' ? this.id() : undefined),
|
||
loader: async ({ params: person }) => {
|
||
const mine = (await this.api.invoke(eegStudies))
|
||
.filter((s) => s.person_id === person && s.analysed)
|
||
.sort((a, b) => b.study_date.localeCompare(a.study_date));
|
||
if (!mine.length) return { study: undefined, analysis: undefined };
|
||
return {
|
||
study: mine[0],
|
||
analysis: await this.api.invoke(eegStudy, { eeg_id: mine[0].id }),
|
||
};
|
||
},
|
||
});
|
||
protected readonly alterations = computed(() =>
|
||
(this.eeg.value()?.analysis?.metrics ?? []).filter((m) => m.outside),
|
||
);
|
||
protected readonly scored = computed(() =>
|
||
(this.eeg.value()?.analysis?.metrics ?? []).some((m) => m.z !== null && m.z !== undefined),
|
||
);
|
||
protected readonly shown = signal<string | undefined>(undefined);
|
||
protected readonly metricNames = METRIC_NAMES;
|
||
protected readonly zoneNames = ZONE_NAMES;
|
||
/** "Zonas más afectadas": the alteration chosen, its zones and electrodes. */
|
||
protected readonly zone = signal<string | undefined>(undefined);
|
||
protected readonly zoned = computed(() => {
|
||
const m = this.alterations().find((a) => a.code === this.zone());
|
||
return m ? { code: m.code, zones: m.zones ?? [], electrodes: m.electrodes ?? [] } : undefined;
|
||
});
|
||
protected readonly zonesScored = computed(() =>
|
||
[...(this.zoned()?.zones ?? []), ...(this.zoned()?.electrodes ?? [])].some(
|
||
(s) => s.z !== null && s.z !== undefined,
|
||
),
|
||
);
|
||
protected readonly biomarkerNames = BIOMARKER_NAMES;
|
||
protected readonly outcomeNames = OUTCOME_NAMES;
|
||
/** "Relación con el ADOS-2": her altered zones (|z| ≥ 2) with a clear association in the
|
||
* cohort (q < 0.05), clearest first, as the old summary showed them. */
|
||
protected readonly related = computed(() =>
|
||
(this.eeg.value()?.analysis?.relation ?? [])
|
||
.filter((f) => Math.abs(f.z) >= 2 && f.q !== null && f.q !== undefined && f.q < 0.05)
|
||
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1)),
|
||
);
|
||
protected qText(q?: number | null): string {
|
||
return q === null || q === undefined ? '—' : q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`;
|
||
}
|
||
protected observed(f: Relation): string {
|
||
if (f.observed === null || f.observed === undefined) return 'Sin dato';
|
||
if (f.kind === 'item')
|
||
return f.observed >= 1 ? `Alterado (${f.observed})` : 'Sin anormalidad (0)';
|
||
return `CSS ${f.observed}`;
|
||
}
|
||
/** Whether what she shows is what the model leans to (above or below one half). */
|
||
protected matches(f: Relation): string | undefined {
|
||
if (f.observed === null || f.observed === undefined) return undefined;
|
||
const present = f.kind === 'item' ? f.observed >= 1 : f.observed >= 8;
|
||
return present === f.probability >= 0.5
|
||
? 'Coincide con la asociación de la cohorte'
|
||
: 'No coincide con la asociación de la cohorte';
|
||
}
|
||
protected readonly zoneOrder = computed(() => byDeviation(this.zoned()?.zones ?? []));
|
||
protected readonly head = computed(() => headMap(this.zoned()?.electrodes ?? []));
|
||
protected readonly curve = computed<Figure>(() => {
|
||
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 levelNames = LEVEL_NAMES;
|
||
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 ?? '') : '';
|
||
});
|
||
}
|