bd897baa2d
rebuild's shell, auth and non-TEA pages; tea/parity's TEA pages on tea/parity's API. - Routes: rebuild's signed-in tree; the TEA risk page joins it (domainAllowed reads the route's data domain when the path has no :domain). - Indicadores: rebuild's header and its generic Resumen/Trazabilidad/Definiciones tabs (TEA as the reference page, fed by tea/parity's measures); TEA Seguimiento and Análisis de riesgo render tea/parity's tea-list inside rebuild's tab-seguimiento/tab-riesgos, which keep rebuild's CaCu/CaMa lists and patient search. rebuild's tab-riesgos-tea read rebuild's TEA Patient extensions, which are gone with its backend; tea-list already shows that list from tea/parity's FHIR search, so it is deleted rather than ported (its look is the base for T8/T9). - Paciente: rebuild's record for CaCu/CaMa; TEA delegates to tea/parity's TeaRecord. rebuild's inline TEA sections read its EEG detail endpoint and are removed. - Gobernanza: tea/parity's page (execution, models with checks/lineage, bundles, training, studies, preview) until T13; model headings use rebuild's model titles. figures.ts: rebuild's scenarios (drawn in the record) plus tea/parity's association forest. - plot.ts: rebuild's layout helpers on tea/parity's partial Plotly bundle. - Conectar: rebuild's KINDS/HELP with an entry for tea/parity's edf node. - Dead code removed: measures boxes/sankey (tea/parity's old TEA tab), eeg-labels headMap/byDeviation/LEVEL_NAMES/METRIC_NAMES (rebuild's TEA record), e2e/layout.ts. - e2e: tea/parity's TEA cases, signed in; rebuild's CaCu/CaMa/site cases need their hospitals loaded and come back with the page suite (T16). - openapi.json and src/app/api: regenerated in the next commit.
349 lines
14 KiB
TypeScript
349 lines
14 KiB
TypeScript
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
|
|
import { ados2Component, ados2Groups } from '../ados2';
|
|
import { code, ext, label, 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,
|
|
groups: [number, number][] = AGE_GROUPS,
|
|
): 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 = groups.find(([lo, hi]) => lo <= age && age <= hi);
|
|
if (found) return `${found[0]}-${found[1]}`;
|
|
return age < groups[0][0] ? `<${groups[0][0]}` : `${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);
|
|
}
|
|
|
|
/** One row of CaMa's follow-up list: her latest mammogram reported by the cut-off, where the
|
|
* biopsy it led to stands, and how soon she should be seen. */
|
|
export interface CamaRow {
|
|
patient: Patient;
|
|
name?: string;
|
|
curp?: string;
|
|
status: string;
|
|
priority: string;
|
|
ageGroup: string;
|
|
/** `days`: from the mammogram to its diagnosis, when known by the cut-off. */
|
|
mammogram: { date: string; birads?: string; days?: number };
|
|
biopsy?: { date: string; histology?: string };
|
|
}
|
|
|
|
export const CAMA_AGE_GROUPS: [number, number][] = [
|
|
[40, 49],
|
|
[50, 59],
|
|
[60, 69],
|
|
];
|
|
|
|
export function camaRows(page: Bundle, cutoff: string): CamaRow[] {
|
|
const reports = resources<DiagnosticReport>(page, 'DiagnosticReport');
|
|
const observations = new Map(resources<Observation>(page, 'Observation').map((o) => [o.id, o]));
|
|
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!]),
|
|
);
|
|
const reported = (r: DiagnosticReport) => ext(r, 'report-date')?.valueDate;
|
|
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
|
|
const mine = reports.filter((r) => r.subject?.reference === `Patient/${patient.id}`);
|
|
const mammogram = mine
|
|
.filter((r) => code(r.code) === 'mammography' && (reported(r) ?? '9') <= cutoff)
|
|
.sort((a, b) => a.effectiveDateTime!.localeCompare(b.effectiveDateTime!))
|
|
.at(-1);
|
|
const exam = mammogram?.effectiveDateTime ?? '';
|
|
const biopsy = mine
|
|
.filter(
|
|
(r) =>
|
|
code(r.code) === 'breast_biopsy' &&
|
|
results(r).get('breast_biopsy.mammogram_exam_date')?.valueDateTime === exam &&
|
|
exam <= (reported(r) ?? '') &&
|
|
reported(r)! <= cutoff,
|
|
)
|
|
.sort((a, b) => reported(a)!.localeCompare(reported(b)!))
|
|
.at(-1);
|
|
return {
|
|
patient,
|
|
name: patient.name?.[0]?.text,
|
|
curp: patient.identifier?.find((i) => i.system === CURP)?.value,
|
|
status: ext(patient, 'follow-up-status')?.valueCoding?.code ?? '',
|
|
priority: ext(patient, 'follow-up-priority')?.valueCoding?.code ?? '',
|
|
ageGroup: ageGroup(patient.birthDate, cutoff, CAMA_AGE_GROUPS),
|
|
mammogram: {
|
|
date: exam,
|
|
birads: mammogram
|
|
? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept)
|
|
: undefined,
|
|
days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined,
|
|
},
|
|
biopsy: biopsy && {
|
|
date: reported(biopsy)!,
|
|
histology: code(results(biopsy).get('breast_biopsy.histology')?.valueCodeableConcept),
|
|
},
|
|
};
|
|
});
|
|
}
|
|
|
|
export const TEA_STEPS = [
|
|
{ code: 'mchat_only', label: 'M-CHAT' },
|
|
{ code: 'psychology', label: 'Psicología' },
|
|
{ code: 'neurology', label: 'Neuropediatría' },
|
|
{ code: 'eeg', label: 'EEG' },
|
|
] as const;
|
|
|
|
type Prediction = NonNullable<RiskAssessment['prediction']>[number];
|
|
|
|
function associationPair(p: Prediction) {
|
|
const stat = (name: string) => ext(p, `association-${name}`)?.valueDecimal;
|
|
return {
|
|
pair: code(p.outcome),
|
|
or: stat('odds-ratio'),
|
|
low: stat('ci-low'),
|
|
high: stat('ci-high'),
|
|
q: stat('q'),
|
|
probability: p.probabilityDecimal,
|
|
reference: stat('reference-probability'),
|
|
sameDirection: ext(p, 'association-same-direction')?.valueBoolean,
|
|
headline: ext(p, 'association-headline')?.valueBoolean === true,
|
|
};
|
|
}
|
|
|
|
function concordance(headline?: ReturnType<typeof associationPair>, ados?: Observation): string {
|
|
if (!headline || !ados || headline.probability == null || headline.reference == null) return '—';
|
|
const outcome = headline.pair?.split('|')[2];
|
|
const item = Number(outcome?.match(/^ados2_item_(\d{2})$/)?.[1]);
|
|
const score =
|
|
outcome === 'CSS' ? ados.valueInteger : ados2Component(ados, item)?.valueQuantity?.value;
|
|
if (score == null) return '—';
|
|
const event = score >= (outcome === 'CSS' ? 8 : 1);
|
|
const predicted = headline.probability >= headline.reference;
|
|
return event === predicted ? 'Concordante' : 'No concordante';
|
|
}
|
|
|
|
function byPatient<T extends DiagnosticReport | Observation | RiskAssessment>(
|
|
records: T[],
|
|
): Map<string | undefined, T[]> {
|
|
const grouped = new Map<string | undefined, T[]>();
|
|
for (const record of records) {
|
|
const subject = record.subject?.reference;
|
|
const group = grouped.get(subject);
|
|
if (group) group.push(record);
|
|
else grouped.set(subject, [record]);
|
|
}
|
|
return grouped;
|
|
}
|
|
|
|
export function teaRows(page: Bundle) {
|
|
const reports = byPatient(resources<DiagnosticReport>(page, 'DiagnosticReport'));
|
|
const observations = byPatient(resources<Observation>(page, 'Observation'));
|
|
const risks = byPatient(resources<RiskAssessment>(page, 'RiskAssessment'));
|
|
const dateOrder = (a: Observation | DiagnosticReport, b: Observation | DiagnosticReport) =>
|
|
(a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '');
|
|
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
|
|
const subject = `Patient/${patient.id}`;
|
|
const obs = observations.get(subject) ?? [];
|
|
const eegs = (reports.get(subject) ?? []).filter((r) => code(r.code) === 'eeg').sort(dateOrder);
|
|
const ados = obs.filter((o) => code(o.code) === 'ados2').sort(dateOrder);
|
|
const mchat = obs.filter((o) => code(o.code) === 'mchat.score').sort(dateOrder)[0];
|
|
const neurology = obs
|
|
.filter(
|
|
(o) =>
|
|
code(o.code) === 'clinical_note.specialty' &&
|
|
code(o.valueCodeableConcept) === 'pediatric_neurology',
|
|
)
|
|
.sort(dateOrder)[0];
|
|
const risk = risks.get(subject)?.[0];
|
|
const pairs = (risk?.prediction ?? []).map(associationPair);
|
|
const headline = pairs.find((p) => p.headline);
|
|
const basisAdos = risk?.basis?.find((ref) =>
|
|
ref.reference?.startsWith('Observation/'),
|
|
)?.reference;
|
|
const evaluation = basisAdos
|
|
? ados.find((o) => `Observation/${o.id}` === basisAdos)
|
|
: ados.at(-1);
|
|
const status = ext(patient, 'follow-up-status')?.valueCoding?.code;
|
|
const dates = [
|
|
mchat?.effectiveDateTime,
|
|
ados[0]?.effectiveDateTime,
|
|
neurology?.effectiveDateTime,
|
|
[
|
|
...eegs.map((e) => e.effectiveDateTime),
|
|
...obs.filter((o) => code(o.code) === 'eeg.lab_record_id').map((o) => o.effectiveDateTime),
|
|
]
|
|
.filter((day) => !!day)
|
|
.sort()[0],
|
|
];
|
|
const explicitStep = TEA_STEPS.findIndex((s) => s.code === ext(patient, 'tea-step')?.valueCode);
|
|
const lastReached =
|
|
explicitStep >= 0
|
|
? explicitStep
|
|
: status === 'finished'
|
|
? 3
|
|
: dates.slice(0, 3).reduce((last, date, index) => (date ? index : last), -1);
|
|
return {
|
|
patient,
|
|
name: patient.name?.[0]?.text,
|
|
recordNumbers: [
|
|
...new Set(
|
|
(patient.identifier ?? [])
|
|
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
|
|
.map((i) => i.value!),
|
|
),
|
|
],
|
|
status,
|
|
steps: TEA_STEPS.map((step, i) => ({
|
|
...step,
|
|
date: dates[i],
|
|
reached: i <= lastReached || (i === 0 && status === 'active'),
|
|
})),
|
|
mchatScore: mchat?.valueQuantity?.value,
|
|
ados: evaluation && {
|
|
date: evaluation.effectiveDateTime,
|
|
css: evaluation.valueInteger,
|
|
module: label(
|
|
evaluation.component?.find((c) => code(c.code) === 'ados2.module')?.valueCodeableConcept,
|
|
),
|
|
classification: label(evaluation.interpretation?.[0]),
|
|
groups: ados2Groups(evaluation),
|
|
},
|
|
eegs: eegs.map((e) => ({
|
|
id: e.id,
|
|
date: e.effectiveDateTime,
|
|
quality: label(e.conclusionCode?.[0]),
|
|
validity: label(e.conclusionCode?.[1]),
|
|
duration: ext(e, 'eeg-duration-min')?.valueDecimal,
|
|
channels: ext(e, 'eeg-channels')?.valueInteger,
|
|
})),
|
|
headline,
|
|
concordance: concordance(headline, evaluation),
|
|
pairs,
|
|
};
|
|
});
|
|
}
|
|
|
|
export type TeaRow = ReturnType<typeof teaRows>[number];
|