From edc32af67e25e6ca46e60dda125a29f417b0b255 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Sun, 29 Nov 2026 12:39:07 -0600 Subject: [PATCH] CaMa record as the old card: summary, mammography, histopathology, prognosis, risk of death and its scenarios' risk factors --- src/app/eeg-labels.ts | 8 ++ src/app/indicadores/follow-up.ts | 6 +- src/app/paciente/factores.ts | 128 +++++++++++++++++++++++++++++ src/app/paciente/paciente.html | 135 ++++++++++++++++++++++--------- src/app/paciente/paciente.scss | 16 +++- src/app/paciente/paciente.ts | 106 ++++++++++++++++++++++-- 6 files changed, 352 insertions(+), 47 deletions(-) create mode 100644 src/app/paciente/factores.ts diff --git a/src/app/eeg-labels.ts b/src/app/eeg-labels.ts index f7b96b4..ea412cd 100644 --- a/src/app/eeg-labels.ts +++ b/src/app/eeg-labels.ts @@ -134,3 +134,11 @@ export function byDeviation(zones: Site[]): Site[] { scored ? Math.abs(b.z ?? 0) - Math.abs(a.z ?? 0) : b.value - a.value, ); } + +/** An EEG's quality level (models.tea.eeg.checks): how much of it the analysis could use. */ +export const LEVEL_NAMES: Record = { + complete: 'registro completo', + partial: 'registro parcial: menos de la mitad limpio', + no_ear_reference: 'sin referencia auricular', + not_analyzable: 'no analizable', +}; diff --git a/src/app/indicadores/follow-up.ts b/src/app/indicadores/follow-up.ts index c389271..435be37 100644 --- a/src/app/indicadores/follow-up.ts +++ b/src/app/indicadores/follow-up.ts @@ -146,11 +146,12 @@ export interface CamaRow { status: string; priority: string; ageGroup: string; - mammogram: { date: string; birads?: 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 }; } -const CAMA_AGE_GROUPS: [number, number][] = [ +export const CAMA_AGE_GROUPS: [number, number][] = [ [40, 49], [50, 59], [60, 69], @@ -196,6 +197,7 @@ export function camaRows(page: Bundle, cutoff: string): CamaRow[] { birads: mammogram ? code(results(mammogram).get('mammography.birads')?.valueCodeableConcept) : undefined, + days: mammogram ? ext(mammogram, 'days-to-diagnosis')?.valueInteger : undefined, }, biopsy: biopsy && { date: reported(biopsy)!, diff --git a/src/app/paciente/factores.ts b/src/app/paciente/factores.ts new file mode 100644 index 0000000..c225c91 --- /dev/null +++ b/src/app/paciente/factores.ts @@ -0,0 +1,128 @@ +import { Component, computed, input, signal } from '@angular/core'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; + +/** One scenario's row of a model's scenario summary (models.factors.scenario_row). */ +export interface ScenarioFactors { + escenario: string; + n_escenario: number; + horizonte_meses?: number; + riesgo_definitorios: string; + riesgo_mayoritarios: string; + incluye_factor_riesgo: boolean; +} + +interface Entry { + text: string; + robust: boolean; +} + +/** A listing cell, `variable=category (robusto|sugerente, share)` separated by `;`. */ +export function entries(cell: string | null | undefined): Entry[] { + return (cell ?? '') + .split(';') + .map((e) => e.trim()) + .filter(Boolean) + .map((text) => ({ text, robust: /\(\s*robusto\b/i.test(text) })); +} + +/** "Factores de riesgo de este escenario", as the old record: per scenario of hers, the risk + * factors present in at least 95 % of it and those in 50 to 95 %, a robust one solid and a + * suggestive one outlined; with a horizon to choose when the model has several. */ +@Component({ + selector: 'app-factores', + imports: [MatFormFieldModule, MatSelectModule], + template: ` +

Factores de riesgo

+ @if (horizons().length > 1) { + + Horizonte + + @for (h of horizons(); track h) { + {{ h }} meses + } + + + } + @for (s of shown(); track s.escenario) { +

+ {{ s.escenario }} (n = {{ s.n }}) +

+ @if (s.defining.length || s.majority.length) { + @if (s.defining.length) { +

Presentes en al menos 95 % del escenario

+ + } + @if (s.majority.length) { +

Presentes en 50 a 95 % del escenario

+ + } + } @else { +

Sin factores de riesgo identificados en este escenario.

+ } + } @empty { +

El informe del modelo no describe factores de sus escenarios.

+ } + `, + styles: ` + .horizon { + margin: 4px 0 8px; + } + .level { + margin: 6px 0 2px; + font-size: 0.85rem; + color: var(--mat-sys-on-surface-variant); + } + .factors { + list-style: none; + padding: 0; + margin: 0 0 6px; + display: flex; + flex-wrap: wrap; + gap: 6px; + } + .factors li { + padding: 2px 10px; + border-radius: 12px; + border: 1px solid var(--mat-sys-primary); + font-size: 0.85rem; + } + .factors li.robust { + background: var(--mat-sys-primary); + color: var(--mat-sys-on-primary); + } + `, +}) +export class Factores { + /** Her scenarios' rows (every horizon when the model has several). */ + readonly rows = input.required(); + protected readonly chosen = signal(undefined); + protected readonly horizons = computed(() => + [ + ...new Set( + this.rows() + .map((r) => r.horizonte_meses) + .filter((h) => h !== undefined), + ), + ].sort((a, b) => a! - b!), + ); + protected readonly horizon = computed(() => this.chosen() ?? this.horizons().at(-1)); + protected readonly shown = computed(() => + this.rows() + .filter((r) => r.horizonte_meses === undefined || r.horizonte_meses === this.horizon()) + .map((r) => ({ + escenario: r.escenario, + n: r.n_escenario, + defining: entries(r.riesgo_definitorios), + majority: entries(r.riesgo_mayoritarios), + })), + ); +} diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index 691751e..f891222 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -6,7 +6,7 @@ } @else if (patient(); as p) {

- {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }} + {{ identity().name ?? 'Paciente' }} {{ p.id!.slice(0, 10) }}

@@ -27,10 +27,37 @@ {{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }}
-
-
Estatus de seguimiento
-
{{ status() }}
-
+ @if (cama(); as c) { +
+
Grupo de edad
+
{{ c.ageGroup || 'No disponible' }}
+
+
+
Escenario clínico
+
{{ c.scenario }}
+
+
+
Estatus de seguimiento
+
+ {{ c.status ?? 'Fuera de la lista (' + c.window + ' meses al ' + c.cutoff + ')' }} +
+
+
+
Prioridad
+
{{ c.priority ?? 'No disponible' }}
+
+
+
Días de mastografía a diagnóstico
+
{{ c.days ?? 'No disponible' }}
+
+ } @else { + @if (status()) { +
+
Estatus de seguimiento
+
{{ status() }}
+
+ } + } @if (p.deceasedDateTime) {
Defunción
@@ -40,6 +67,40 @@
+ @if (cama(); as c) { + + Mastografía + +

Última mastografía

+
+
+
Categoría BI-RADS
+
{{ c.birads ?? 'No disponible' }}
+
+
+
Fecha
+
{{ c.mammogram ?? 'No disponible' }}
+
+
+
+
+ + Histopatología + +

Resultado histopatológico

+
+
+
Resultado
+
{{ c.histology ?? 'No disponible' }}
+
+
+
Fecha de reporte de la biopsia
+
{{ c.biopsy ?? 'No disponible' }}
+
+
+
+
+ } Historial médico @@ -178,7 +239,7 @@ Estudio del {{ st.study_date }}: {{ st.valid ? 'aceptable para el análisis' : 'no aceptable' }} @if (st.level) { - ({{ st.level }}) + ({{ levelNames[st.level] ?? st.level }}) }

Alteraciones del EEG

@@ -352,41 +413,13 @@
} - @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { - - Análisis de supervivencia - - @if (survival.isLoading()) { - - } @else if (survival.value(); as s) { -

Escenario clínico de la paciente

-
    - @for (name of s.scenarios; track name) { -
  • {{ name }}
  • - } -
- @for (f of s.figures; track f.title) { -

{{ f.title }}

- - } @empty { -

- Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas. -

- } - } @else if (survival.error()) { - - } -
-
- } @if (recurrenceModel(); as rm) { Análisis de recurrenciaPronóstico y recomendaciones +

Análisis de recurrencia

@@ -420,12 +453,42 @@ Sus escenarios tienen menos recaídas de las necesarias para trazar curvas.

} + } @else if (recurrence.error()) { } } + @if (models().some((m) => m.model.endsWith('.survival') && m.scenarios.length)) { + + Riesgo de muerte + +

Análisis de supervivencia

+ @if (survival.isLoading()) { + + } @else if (survival.value(); as s) { +

Escenario clínico de la paciente

+
    + @for (name of s.scenarios; track name) { +
  • {{ name }}
  • + } +
+ @for (f of s.figures; track f.title) { +

{{ f.title }}

+ + } @empty { +

+ Sus escenarios tienen menos fallecimientos de los necesarios para trazar curvas. +

+ } + + } @else if (survival.error()) { + + } +
+
+ } } @else if (loading()) { diff --git a/src/app/paciente/paciente.scss b/src/app/paciente/paciente.scss index a75cfe8..23a5a44 100644 --- a/src/app/paciente/paciente.scss +++ b/src/app/paciente/paciente.scss @@ -1,16 +1,19 @@ -.summary { +.summary, +.facts { display: flex; flex-wrap: wrap; gap: var(--space-6); margin: var(--space-3) 0 var(--space-4); } -.summary dt { +.summary dt, +.facts dt { color: var(--color-text-secondary); font-size: 12px; } -.summary dd { +.summary dd, +.facts dd { font-weight: 500; margin: 0; } @@ -88,3 +91,10 @@ tr.chosen td { font-size: 0.8em; } } + +h1 .id { + font-size: 14px; + font-weight: 400; + margin-left: var(--space-2); + vertical-align: middle; +} diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index da001cd..d1b9315 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -19,8 +19,8 @@ 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 { CURP } from '../indicadores/follow-up'; -import { LABELS, name } from '../indicadores/measures'; +import { ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; +import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { BIOMARKER_NAMES, byDeviation, @@ -28,10 +28,12 @@ import { 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 { @@ -49,7 +51,16 @@ function shown(o: Observation): string { * champion models' risks with their curves. Everything read from the FHIR API. */ @Component({ selector: 'app-paciente', - imports: [Loading, DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot], + imports: [ + Factores, + Loading, + DecimalPipe, + MatButtonModule, + MatCardModule, + MatIconModule, + RouterLink, + Plot, + ], templateUrl: './paciente.html', styleUrl: './paciente.scss', }) @@ -58,6 +69,9 @@ export class Paciente { private readonly api = inject(Api); 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(); private readonly data = resource({ params: () => ({ domain: this.domain(), id: this.id() }), @@ -117,7 +131,11 @@ export class Paciente { reported: ext(r, 'report-date')?.valueDate, kind: label(r.code), status: r.status, - results: [...results.map((o) => `${label(o.code)}: ${shown(o)}`)], + // "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}`; + }), }; }); }); @@ -175,7 +193,16 @@ export class Paciente { 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( @@ -188,6 +215,7 @@ export class Paciente { }; } return { + factors: mine((report?.['factores_escenarios'] ?? []) as any[]) as ScenarioFactors[], scenarios: m.scenarios, figures: mine((report?.['escenarios'] ?? []) as any[]).map((e) => scenarioFigure( @@ -338,7 +366,7 @@ export class Paciente { x, y: m.predictions.map((p) => p.p * 100), mode: 'lines+markers', - name: m.model.replace('cacu.', ''), + name: m.text.replace(/ v\d+$/, ''), line: { color }, }, ]; @@ -358,12 +386,78 @@ export class Paciente { 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, - numbers: (p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.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(() => {