Files
WebApp/src/app/indicadores/follow-up.ts
T
2026-11-25 16:17:23 -06:00

135 lines
5.5 KiB
TypeScript

import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { code, ext, resources } from '../fhir';
/** One row of the follow-up list: what the list shows of a patient at the cut-off. */
export interface Row {
patient: Patient;
name?: string;
curp?: string;
status: string;
ageGroup: string;
cytology?: { date: string; result?: string; adequacy?: string };
hpv?: { date: string; positive: boolean; types1618?: boolean };
daysToDiagnosis?: number;
biopsy?: { date: string; histology?: string };
risk: Record<'cin2' | 'cancer', number | undefined>;
}
export const CURP = 'https://isssteleon.org/fhir/sid/curp';
const AGE_GROUPS: [number, number][] = [
[25, 34],
[35, 44],
[45, 54],
[55, 64],
];
export function ageGroup(birth: string | undefined, at: string): string {
if (!birth) return 'Sin dato';
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = at.split('-').map(Number);
const age = y - by - (m < bm || (m === bm && d < bd) ? 1 : 0);
const found = AGE_GROUPS.find(([lo, hi]) => lo <= age && age <= hi);
if (found) return `${found[0]}-${found[1]}`;
return age < AGE_GROUPS[0][0] ? `<${AGE_GROUPS[0][0]}` : `${AGE_GROUPS.at(-1)![1] + 1}+`;
}
/** Her current risk of an outcome at a horizon: from the latest index date any of the
* outcome's models scored her at, the highest when several did (as the list is sorted). */
export function currentRisk(
risks: RiskAssessment[],
outcome: 'cin2' | 'cancer',
horizon: number,
): number | undefined {
const mine = risks
.filter((r) => code(r.method)?.startsWith(`cacu.${outcome}`))
.flatMap((r) =>
(r.prediction ?? [])
.filter((p) => p.whenRange?.high?.value === horizon)
.map((p) => ({ r, p })),
);
if (!mine.length) return undefined;
const latest = mine
.map((x) => x.r.occurrenceDateTime ?? '')
.sort()
.at(-1);
return Math.max(
...mine
.filter((x) => x.r.occurrenceDateTime === latest)
.map((x) => x.p.probabilityDecimal ?? 0),
);
}
/** The list's rows from one page: per patient, her latest cytology and HPV sampled in the
* window, her days to diagnosis, and her latest reported biopsy. */
export function rows(page: Bundle, start: string, cutoff: string, horizon: number): Row[] {
const reports = resources<DiagnosticReport>(page, 'DiagnosticReport');
const observations = new Map(resources<Observation>(page, 'Observation').map((o) => [o.id, o]));
const risks = resources<RiskAssessment>(page, 'RiskAssessment');
const results = (r: DiagnosticReport) =>
new Map(
(r.result ?? [])
.map((x) => observations.get(x.reference?.split('/')[1]))
.filter((o) => !!o)
.map((o) => [code(o!.code), o!]),
);
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
const mine = reports.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
const by = (kind: string) => mine.filter((r) => code(r.code) === kind);
const cytologies = by('cervical_cytology')
.filter((r) => start <= r.effectiveDateTime! && r.effectiveDateTime! <= cutoff)
.sort((a, b) => a.effectiveDateTime!.localeCompare(b.effectiveDateTime!));
const last = cytologies.at(-1);
const lastResults = last ? results(last) : new Map();
const hpv = cytologies.filter((r) => results(r).has('cervical_cytology.hpv')).at(-1);
const hpvResults = hpv ? results(hpv) : new Map();
const types = ['cervical_cytology.hpv_16', 'cervical_cytology.hpv_18']
.filter((k) => hpvResults.has(k))
.map((k) => hpvResults.get(k)!.valueBoolean);
const biopsy = by('cervical_biopsy')
.filter((r) => ext(r, 'report-date'))
.sort((a, b) =>
ext(a, 'report-date')!.valueDate!.localeCompare(ext(b, 'report-date')!.valueDate!),
)
.at(-1);
const theirs = risks.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
return {
patient,
name: patient.name?.[0]?.text,
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
ageGroup: ageGroup(patient.birthDate, cutoff),
cytology: last && {
date: last.effectiveDateTime!,
result: code(lastResults.get('cervical_cytology.result')?.valueCodeableConcept),
adequacy: code(lastResults.get('cervical_cytology.adequacy')?.valueCodeableConcept),
},
hpv: hpv && {
date: hpv.effectiveDateTime!,
positive: !!hpvResults.get('cervical_cytology.hpv')?.valueBoolean,
types1618: types.length ? types.some((t) => t) : undefined,
},
daysToDiagnosis: last ? ext(last, 'days-to-diagnosis')?.valueInteger : undefined,
biopsy: biopsy && {
date: ext(biopsy, 'report-date')!.valueDate!,
histology: code(results(biopsy).get('cervical_biopsy.histology')?.valueCodeableConcept),
},
risk: {
cin2: currentRisk(theirs, 'cin2', horizon),
cancer: currentRisk(theirs, 'cancer', horizon),
},
};
});
}
/** The window's first day: `months` before the cut-off (the month's last day when shorter), plus one. */
export function windowStart(cutoff: string, months: number): string {
const [y, m, d] = cutoff.split('-').map(Number);
const total = y * 12 + (m - 1) - months;
const year = Math.floor(total / 12);
const month = total % 12;
const last = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
const day = new Date(Date.UTC(year, month, Math.min(d, last) + 1));
return day.toISOString().slice(0, 10);
}