2add96e38a
Add a label above each completed timeline diamond and a baseline tick at each completed step date, retaining the dotted line and day annotations. Group each study and metric into one alterations block with its fields, head map and age norm. Name the centile bands, shorten the norm title, explain the head-map z scale and use Puntas paroxísticas consistently in the shared biomarker labels. Update the logic and page expectations. Choices left open by the spec: - Use label annotations shifted upward by 26 pixels and a 40-pixel top margin; retain the existing categorical axis and pending annotations. Use the completed dates as explicit date-axis ticks. - Add an optional charts array for the grouped row while retaining chart for standalone plots. Put the map first and norm second, omit absent figures, and keep a block even when neither figure is available. - Use two equal grid columns with the existing space-4 gap, stacking at 800 pixels. Separate adjacent blocks with the existing border color, space-6 margin and space-4 padding. - Keep grouped figures in the PDF export's existing sequential image order, consuming one image for each figure. - Make bandFill's final name parameter optional and show its legend only when a name is supplied, preserving unnamed governance bands. - Keep the existing lighter outer/darker inner band drawing order. - Keep tea-data.ts unchanged: its spike title already matches the required Puntas paroxísticas. Preserve the existing spike exclusion in loadNorms. Verification: git diff --check passed. Prettier skipped because this worktree has no WebApp/node_modules/.bin/prettier. Angular tests/build and browser page tests were not run on the saturated lab server, as specified. No API signatures, schemas or endpoints changed.
447 lines
16 KiB
TypeScript
447 lines
16 KiB
TypeScript
import { DecimalPipe } from '@angular/common';
|
|
import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core';
|
|
import { MatButtonModule } from '@angular/material/button';
|
|
import { MatCardModule } from '@angular/material/card';
|
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
|
import { MatIconModule } from '@angular/material/icon';
|
|
import { MatSelectModule } from '@angular/material/select';
|
|
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
|
|
import { RouterLink } from '@angular/router';
|
|
import type {
|
|
Condition,
|
|
DiagnosticReport,
|
|
Observation,
|
|
Patient,
|
|
Procedure,
|
|
RiskAssessment,
|
|
} from 'fhir/r4';
|
|
import { Api } from '../api/api';
|
|
import { curve } from '../api/fn/models/curve';
|
|
import { readReport$Json } from '../api/fn/models/read-report-json';
|
|
import type { Domain } from '../api/models/domain';
|
|
import {
|
|
code,
|
|
CURP,
|
|
ext,
|
|
extensions,
|
|
Fhir,
|
|
label,
|
|
patientCurp,
|
|
patientName,
|
|
resources,
|
|
} from '../fhir';
|
|
import { type Centile, scenarioFigure } from '../gobernanza/figures';
|
|
import { ageGroup, CAMA_AGE_GROUPS, camaRows } from '../indicadores/follow-up';
|
|
import { SHORT } from '../indicadores/figures';
|
|
import { LABELS, name, PRIORITY } from '../indicadores/measures';
|
|
import { Figure, PALETTE, Plot } from '../plot';
|
|
import { Loading } from '../loading';
|
|
import { Factores, ScenarioFactors } from './factores';
|
|
import { identityRows, loadTeaPatient, Study } from './tea-data';
|
|
import { ageNorm } from './tea-figures';
|
|
import { TeaSection } from './tea-section';
|
|
import {
|
|
exportTeaPdf,
|
|
forestTitle,
|
|
probabilityTitle,
|
|
recordSections,
|
|
riskSections,
|
|
Section,
|
|
} from './tea-sections';
|
|
|
|
function shown(o: Observation): string {
|
|
if (o.valueBoolean !== undefined) return o.valueBoolean ? 'positivo' : 'negativo';
|
|
if (o.valueCodeableConcept) {
|
|
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 ?? '';
|
|
}
|
|
|
|
@Component({
|
|
selector: 'app-paciente',
|
|
imports: [
|
|
Factores,
|
|
Loading,
|
|
DecimalPipe,
|
|
MatButtonModule,
|
|
MatCardModule,
|
|
MatFormFieldModule,
|
|
MatIconModule,
|
|
MatSelectModule,
|
|
MatSlideToggleModule,
|
|
RouterLink,
|
|
Plot,
|
|
TeaSection,
|
|
],
|
|
templateUrl: './paciente.html',
|
|
styleUrl: './paciente.scss',
|
|
})
|
|
export class Paciente {
|
|
private readonly fhir = inject(Fhir);
|
|
private readonly api = inject(Api);
|
|
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
|
readonly domain = input.required<string>();
|
|
readonly id = input.required<string>();
|
|
readonly ventana = input<string>();
|
|
readonly corte = input<string>();
|
|
readonly risk = input(false);
|
|
|
|
private readonly data = resource({
|
|
params: () => (this.domain() === 'tea' ? undefined : { 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),
|
|
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 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,
|
|
results: results.map((o) => {
|
|
const [name, value] = [label(o.code), shown(o)];
|
|
return value.startsWith(name) ? value : `${name}: ${value}`;
|
|
}),
|
|
};
|
|
});
|
|
});
|
|
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 ?? '',
|
|
scenarios: extensions(r, '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,
|
|
})),
|
|
}));
|
|
});
|
|
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;
|
|
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)',
|
|
),
|
|
),
|
|
};
|
|
},
|
|
});
|
|
}
|
|
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 },
|
|
yaxis: {
|
|
title: { text: 'Probabilidad (%)' },
|
|
range: [0, Math.max(5, this.top() * 110)],
|
|
tickformat: SHORT,
|
|
hoverformat: SHORT,
|
|
},
|
|
},
|
|
};
|
|
});
|
|
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 patientName = patientName;
|
|
protected readonly identity = computed(() => {
|
|
const p = this.patient();
|
|
return {
|
|
name: patientName(p),
|
|
curp: patientCurp(p),
|
|
numbers: [
|
|
...new Set(
|
|
(p?.identifier ?? []).filter((i) => i.system !== CURP).map((i) => i.value ?? ''),
|
|
),
|
|
].filter(Boolean),
|
|
};
|
|
});
|
|
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;
|
|
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 ?? '') : '';
|
|
});
|
|
protected readonly tea = resource({
|
|
params: () => (this.domain() === 'tea' ? this.id() : undefined),
|
|
loader: ({ params }) => loadTeaPatient(this.fhir, params),
|
|
});
|
|
protected readonly norms = resource({
|
|
params: () => (this.risk() || !this.tea.hasValue() ? undefined : this.tea.value().studies),
|
|
loader: ({ params }) => this.loadNorms(params),
|
|
});
|
|
protected readonly onlyAltered = signal(false);
|
|
protected readonly selectedKey = signal('');
|
|
protected readonly selectedPair = computed(() => {
|
|
const pairs = this.tea.hasValue() ? this.tea.value().pairs : [];
|
|
return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0];
|
|
});
|
|
protected readonly teaIdentity = computed(() =>
|
|
this.tea.hasValue() ? identityRows(this.tea.value().patient) : [],
|
|
);
|
|
protected readonly teaSections = computed<Section[]>(() => {
|
|
if (!this.tea.hasValue()) return [];
|
|
const patient = this.tea.value();
|
|
return this.risk()
|
|
? riskSections(patient, this.onlyAltered(), this.selectedPair())
|
|
: recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map());
|
|
});
|
|
protected readonly forestTitle = forestTitle;
|
|
protected readonly probabilityTitle = probabilityTitle;
|
|
protected readonly exporting = signal(false);
|
|
protected readonly exportError = signal(false);
|
|
|
|
private async loadNorms(studies: Study[]) {
|
|
const curves = new Map<string, Promise<Centile[]>>();
|
|
const charts = await Promise.all(
|
|
studies.flatMap((eeg) =>
|
|
eeg.metrics.map(async (metric) => {
|
|
const model = /^tea\.([^/]+)\/([1-9]\d*)$/.exec(metric.model ?? '');
|
|
if (
|
|
!model ||
|
|
metric.key === 'paroxysmal_spikes' ||
|
|
metric.value == null ||
|
|
eeg.age == null
|
|
) {
|
|
return undefined;
|
|
}
|
|
const [, name, version] = model;
|
|
const key = model[0];
|
|
if (!curves.has(key)) {
|
|
curves.set(
|
|
key,
|
|
this.api
|
|
.invoke(curve, { domain: 'tea', name, version: Number(version) })
|
|
.then((rows) => rows as Centile[])
|
|
.catch(() => []),
|
|
);
|
|
}
|
|
const rows = await curves.get(key)!;
|
|
if (!rows.some((row) => row.median != null)) return undefined;
|
|
return [
|
|
`${eeg.id}|${metric.key}`,
|
|
{
|
|
title: 'Norma por edad',
|
|
figure: ageNorm(rows, metric, eeg.age),
|
|
},
|
|
] as const;
|
|
}),
|
|
),
|
|
);
|
|
return new Map(charts.filter((chart) => chart !== undefined));
|
|
}
|
|
|
|
protected async download(): Promise<void> {
|
|
this.exportError.set(false);
|
|
this.exporting.set(true);
|
|
try {
|
|
await exportTeaPdf(
|
|
this.risk() ? 'riesgos' : 'seguimiento',
|
|
this.risk() ? 'Análisis de riesgo TEA' : 'Expediente TEA',
|
|
this.teaSections(),
|
|
this.host.nativeElement.querySelectorAll<HTMLDivElement>('app-plot .plot'),
|
|
);
|
|
} catch {
|
|
this.exportError.set(true);
|
|
} finally {
|
|
this.exporting.set(false);
|
|
}
|
|
}
|
|
}
|