import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { RouterLink } from '@angular/router'; import { Api } from '../api/api'; import { curve } from '../api/fn/models/curve'; import { Fhir } from '../fhir'; import { Plot } from '../plot'; import { loadTeaPatient, Study } from './tea-data'; import { ageNorm, Centile, forest, probabilityCurve, zBars } from './tea-figures'; import { calculation, exportTeaPdf, forestTitle, limitations, probabilityRows, probabilityTitle, recordSections, Section, } from './tea-sections'; @Component({ selector: 'app-tea-section', imports: [MatCardModule, Plot], templateUrl: './tea-section.html', styleUrl: './tea-section.scss', }) export class TeaSection { readonly section = input.required
(); } @Component({ selector: 'app-tea-record', imports: [TeaSection, RouterLink, MatButtonModule], templateUrl: './tea-record.html', }) export class TeaRecord { private readonly fhir = inject(Fhir); private readonly api = inject(Api); private readonly host = inject>(ElementRef); readonly id = input.required(); protected readonly patient = resource({ params: () => this.id(), loader: ({ params }) => loadTeaPatient(this.fhir, params), }); protected readonly norms = resource({ params: () => (this.patient.hasValue() ? this.patient.value().studies : undefined), loader: ({ params }) => this.loadNorms(params), }); protected readonly sections = computed(() => { const patient = this.patient.hasValue() ? this.patient.value() : undefined; return patient ? recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map()) : []; }); protected readonly exporting = signal(false); protected readonly exportError = signal(false); private async loadNorms(studies: Study[]) { const curves = new Map>(); 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 · p5–p95', figure: ageNorm(rows, metric, eeg.age), }, ] as const; }), ), ); return new Map(charts.filter((chart) => chart !== undefined)); } protected async download(): Promise { this.exportError.set(false); this.exporting.set(true); try { await exportTeaPdf( 'seguimiento', 'Expediente TEA', this.sections(), this.host.nativeElement.querySelectorAll('app-plot .plot'), ); } catch { this.exportError.set(true); } finally { this.exporting.set(false); } } } @Component({ selector: 'app-tea-risk', imports: [TeaSection, RouterLink, MatButtonModule], templateUrl: './tea-risk.html', }) export class TeaRisk { private readonly fhir = inject(Fhir); private readonly host = inject>(ElementRef); readonly id = input.required(); protected readonly patient = resource({ params: () => this.id(), loader: ({ params }) => loadTeaPatient(this.fhir, params), }); protected readonly onlyAltered = signal(false); protected readonly selectedKey = signal(''); protected readonly selectedPair = computed(() => { const pairs = this.patient.hasValue() ? this.patient.value().pairs : []; return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0]; }); protected readonly forestTitle = forestTitle; protected readonly probabilityTitle = probabilityTitle; protected readonly sections = computed(() => { if (!this.patient.hasValue()) return []; const patient = this.patient.value(); const studies = patient.riskStudy ? [patient.riskStudy] : patient.studies; const scores = studies .map((eeg) => ({ date: eeg.date, figure: zBars(eeg) })) .find(({ figure }) => figure.data[0].x?.length); const effects = forest(patient.pairs, this.onlyAltered()); const pair = this.selectedPair(); return [ { title: 'Qué calcula', blocks: [{ text: calculation }] }, { title: 'Puntuaciones z por métrica y zona', blocks: scores ? [ { chart: { title: scores.date, figure: scores.figure, height: Math.max(340, 24 * (scores.figure.data[0].x?.length ?? 0) + 80), }, }, ] : [], }, { title: forestTitle, blocks: [ effects.data[0].x?.length ? { chart: { title: 'OR e IC 95 %', figure: effects, height: Math.max(340, 26 * effects.data[0].x.length + 80), }, } : { text: '—' }, ], }, { title: 'Probabilidad frente a la referencia', blocks: [{ table: probabilityRows(patient.pairs) }], }, { title: probabilityTitle, blocks: pair ? [{ chart: { title: pair.title, figure: probabilityCurve(pair) } }] : [], }, { title: 'Limitaciones', blocks: [{ text: limitations }] }, ]; }); protected readonly exporting = signal(false); protected readonly exportError = signal(false); protected async download(): Promise { this.exportError.set(false); this.exporting.set(true); try { await exportTeaPdf( 'riesgos', 'Análisis de riesgo TEA', this.sections(), this.host.nativeElement.querySelectorAll('app-plot .plot'), ); } catch { this.exportError.set(true); } finally { this.exporting.set(false); } } }