Files
WebApp/src/app/paciente/paciente.ts
T
2026-12-03 10:23:42 -06:00

734 lines
31 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 { type Insufficient, insufficientText, sortUndrawn } from './survival-scenarios';
import { cacuEligibility } from '../api/fn/fhir/cacu-eligibility';
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 { camaRecordSheets } from './cama-record-sheets';
import { recordSheets } from './record-sheets';
import { HttpClient } from '@angular/common/http';
import type { Parameters as FhirParameters } from 'fhir/r4';
import { firstValueFrom } from 'rxjs';
import { ApiConfiguration } from '../api/api-configuration';
import { ANTECEDENTS, Fact, group, hpvApart, split } from './record-groups';
import { eligibilityFailure, eligibilityView, type EligibilityState } from './eligibility';
import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve';
import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationOf, noCurveText, survivalFigure } from './survival-combination';
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';
import { CurveChooser, figureChoices } from './curve-chooser';
/** 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 ?? '';
}
/** A report's Observations as facts of its study's form (record-groups). */
function facts(observations: Observation[]): Fact[] {
return observations.map((o) => ({
...split(code(o.code) ?? ''),
title: label(o.code),
value: shown(o),
}));
}
/** One patient: her history (conditions, procedures), her tests and results, and the
* champion models' risks with their curves. Everything read from the FHIR API. */
/** The names of the methods the figures draw, each once. */
function methods(figures: { figure: { data: unknown[] } }[]): string[] {
const names = figures.flatMap((f) => f.figure.data.map((t) => (t as { name?: string }).name));
return [...new Set(names.filter((n): n is string => !!n))];
}
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({
selector: 'app-paciente',
imports: [
Factores,
CurveChooser,
Loading,
DecimalPipe,
MatButtonModule,
MatCardModule,
MatIconModule,
RouterLink,
Plot,
RiskScales,
RiskSeries,
Stages,
],
templateUrl: './paciente.html',
styleUrl: './paciente.scss',
})
export class Paciente {
private readonly fhir = inject(Fhir);
private readonly api = inject(Api);
private readonly http = inject(HttpClient);
private readonly root = inject(ApiConfiguration).rootUrl;
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));
});
protected readonly cutoff = computed(() => this.corte() ?? new Date().toLocaleDateString('sv'));
protected readonly age = computed(() => ageAt(this.patient()?.birthDate, this.cutoff()));
/** Why she has no risk estimate; nothing when she is eligible. The backend's reason first; the
* hysterectomy of her record is still held against her when the backend does not report it,
* as with evidence loaded without the day it was available. */
protected readonly riskExclusion = computed(() => {
if (this.domain() !== 'cacu') return undefined;
const patient = this.patient();
const sample = this.citologia()?.slice(0, 10);
const index = sample && sample < this.cutoff() ? sample : this.cutoff();
const status = (patient && ext(patient, 'follow-up-status')?.valueCoding?.code) ?? '';
const reported = ineligibility(this.eligibility(), status, index);
if (reported) return reported;
const recorded = patient && ext(patient, 'first-hysterectomy-recorded')?.valueDate;
return recorded && recorded <= index
? `No disponible por: histerectomía registrada el ${recorded}.`
: undefined;
});
/** 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;
});
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
);
/** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
* survival only there is nothing to draw here: its scales are in the survival section. */
protected readonly groups = computed(() =>
this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
? riskGroups(this.riskModels())
: [],
);
protected readonly survivalScales = computed(() =>
this.domain() === 'cacu'
? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
: [],
);
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
* the model version that scored her. */
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
},
loader: async ({ params: { version, inputs } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: 'cacu' as Domain,
name: 'survival',
version,
report: 'interpretability',
});
const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km
? { n: found.n, fallecidos: found.fallecidos, curves: figureChoices(survivalFigure(found)) }
: { missing: noCurveText(report as Record<string, unknown>, found) };
},
});
/** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({
params: () =>
this.domain() === 'cacu'
? { id: this.id(), cutoff: this.corte(), sample: this.citologia() }
: undefined,
loader: async ({ params }): Promise<Series[] | undefined> => {
try {
const answer = await firstValueFrom(
this.http.get<FhirParameters>(
`${this.root}/cacu/fhir/Patient/${params.id}/$risk-series`,
{
params: Object.fromEntries(
Object.entries({
cutoff: params.cutoff,
sample: params.sample?.slice(0, 10),
}).filter((e): e is [string, string] => !!e[1]),
),
},
),
);
return parseSeries(answer);
} catch {
return undefined;
}
},
});
/** CaCu: the eligibility the backend publishes for each indexed visit (`$eligibility`). A failure is a
* state of the section, never an eligibility; a new patient starts from nothing (no earlier answer). */
private readonly eligibilityData = resource({
params: () => (this.domain() === 'cacu' ? { id: this.id(), cutoff: this.corte() } : undefined),
loader: async ({ params }): Promise<EligibilityState> => {
try {
const answer = await this.api.invoke(cacuEligibility, {
domain: 'cacu' as Domain,
id: params.id,
cutoff: params.cutoff,
});
return eligibilityView(answer as FhirParameters);
} catch (error) {
return eligibilityFailure(error);
}
},
});
protected readonly eligibility = computed<EligibilityState>(() =>
this.eligibilityData.isLoading()
? { kind: 'loading' }
: (this.eligibilityData.value() ?? { kind: 'loading' }),
);
protected readonly saving = signal(false);
protected readonly saveError = signal('');
/** Her record as a PDF (CaCu's or CaMa's). */
protected async save(): Promise<void> {
this.saving.set(true);
this.saveError.set('');
try {
if (this.domain() === 'cama') {
await this.saveCama();
return;
}
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()],
];
if (this.riskExclusion()) facts.push(['Evaluación de riesgo', this.riskExclusion()]);
const sheets = recordSheets(
facts,
this.stages() ?? [],
this.history(),
this.tests(),
this.forms(),
this.scales(),
);
await savePdf(sheets, 'expediente-cacu');
} catch {
this.saveError.set('No se generó el archivo.');
} finally {
this.saving.set(false);
}
}
/** CaMa: her record as a PDF, with what CaMa publishes of her. */
private async saveCama(): Promise<void> {
const c = this.cama();
const { name: who, curp, numbers } = this.identity();
const p = this.patient();
const facts: [string, string | undefined][] = [
['Nombre', who],
['CURP', curp],
['Expedientes', numbers.join(', ')],
['Fecha de nacimiento', p?.birthDate],
['Sexo', p?.gender === 'female' ? 'Femenino' : p?.gender === 'male' ? 'Masculino' : undefined],
['Grupo de edad', c?.ageGroup],
['Escenario clínico', c?.scenario],
['Fecha de corte', c?.cutoff],
[
'Estatus de seguimiento',
c ? (c.status ?? `Fuera de la lista (${c.window} meses al ${c.cutoff})`) : undefined,
],
['Prioridad', c?.priority],
['Días de mastografía a diagnóstico', c?.days?.toString()],
...(p?.deceasedDateTime ? ([['Defunción', p.deceasedDateTime]] as [string, string][]) : []),
];
const studies: [string, string | undefined][] = [
['Categoría BI-RADS de la última mastografía', c?.birads],
['Fecha de la última mastografía', c?.mammogram],
['Resultado histopatológico', c?.histology],
['Fecha de reporte de la biopsia', c?.biopsy],
];
const analysis = (title: string, r: typeof this.survival) => {
// a report that failed to load is no analysis: its absence is said, the file is still made
const v = r.hasValue() ? r.value() : undefined;
return v
? [{ title, scenarios: v.scenarios, figures: v.figures.map((f) => f.title), undrawn: v.unavailable }]
: [];
};
const sheets = camaRecordSheets(
facts,
studies,
this.history(),
this.tests(),
this.models(),
[...analysis('Supervivencia', this.survival), ...analysis('Recurrencia', this.recurrence)],
);
await savePdf(sheets, 'expediente-cama');
}
protected readonly tests = computed(() => {
const d = this.data.value();
if (!d) return [];
return d.reports.flatMap((r) => {
const results = (r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[];
// the study's own results; the form's antecedents are in their own section and the extra
// findings are collapsed (record-groups)
const { hpv, rest } = hpvApart(facts(results));
const found = group(rest);
const row = {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
kind: label(r.code),
status: r.status,
results: found.results,
findings: found.findings,
};
// an HPV result is a study of its own: its own row, only when there is one
return hpv.length
? [row, { ...row, kind: 'Prueba de VPH', results: group(hpv).results, findings: [] }]
: [row];
});
});
/** CaCu: what each cytology's form declares (her antecedents and the exploration), the one she was
* opened at first, each with its day. They are statements of the form, not confirmed diagnoses. */
protected readonly forms = computed(() => {
const d = this.data.value();
if (!d || this.domain() !== 'cacu') return [];
const cytologies = d.reports.filter((r) => code(r.code) === 'cervical_cytology');
const first = cytologies.find((r) => r.effectiveDateTime === this.citologia()) ?? cytologies[0];
return [first, ...cytologies.filter((r) => r !== first)]
.filter((r) => !!r)
.map((r) => {
const found = group(
facts(
(r.result ?? [])
.map((x) => d.observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o) as Observation[],
),
).antecedents;
return {
date: r.effectiveDateTime ?? '',
reported: ext(r, 'report-date')?.valueDate,
values: found,
};
})
.filter((f) => ANTECEDENTS.some((a) => f.values[a.field]));
});
protected readonly antecedents = ANTECEDENTS;
/** One model's latest risk assessment per model. */
protected readonly models = computed(() => {
if (this.riskExclusion()) return [];
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 ?? '',
measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// 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,
unavailable: [] as string[],
insufficient: [] as Insufficient[],
missing: [] as string[],
methods: [] as string[],
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',
),
),
};
}
const drawn = mine((report?.['escenarios'] ?? []) as any[]);
const figures = drawn.map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
e,
e.horizons_months,
'Supervivencia S(t)',
),
);
const undrawn = m.scenarios.filter((s) => !drawn.some((e) => e.escenario === s));
// CaCu: the report says which scenarios lack deaths (`escenarios_sin_curvas`); one it does not
// mention is not "insufficient", it is absent from the report. Other domains keep one list.
const { insufficient, missing } =
domain === 'cacu' ? sortUndrawn(report, undrawn) : { insufficient: [], missing: [] };
return {
factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[],
scenarios: m.scenarios,
figures,
// her scenarios the report draws no curve for
unavailable: domain === 'cacu' ? [] : undrawn,
insufficient,
missing,
methods: methods(figures),
};
},
});
}
/** 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 ?? []));
/** The institutional models' curves, drawn at the horizons each publishes (risk-curve). */
protected readonly curve = computed<Figure>(() => curveFigure(this.riskModels(), this.top()));
private top(): number {
return Math.max(
0,
...this.riskModels().flatMap((m) => m.predictions.map((p) => p.high ?? p.p)),
);
}
protected readonly insufficientText = insufficientText;
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 ?? '') : '';
});
}