import { HttpClient, HttpParams } from '@angular/common/http'; import { Component, ElementRef, inject, OnDestroy, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { RouterLink } from '@angular/router'; import { forkJoin, Subscription } from 'rxjs'; type Resource = any; type Section = 'resumen' | 'historico' | 'seguimiento'; type State = 'inicial' | 'cargando' | 'listo' | 'error'; const stages: Record = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' }; const populations: Record = { 'initial-population': 'Total', numerator: 'Numerador', denominator: 'Denominador', 'denominator-exclusion': 'Excluidos del denominador', 'measure-observation': 'Con valor', 'measure-population-exclusion': 'Sin valor' }; const code = (value: Resource) => value?.coding?.[0]?.code ?? ''; const text = (value: Resource) => value?.coding?.[0]?.display ?? value?.text ?? code(value); const resources = (bundle: Resource): Resource[] => (bundle?.entry ?? []).map((entry: Resource) => entry.resource); const simulated = (resource: Resource) => resource?.meta?.tag?.some((tag: Resource) => tag.system === 'https://isssteleon.org/fhir/CodeSystem/etiqueta' && tag.code === 'simulado'); @Component({ selector: 'app-tea-status-page', imports: [FormsModule, RouterLink], templateUrl: './tea-status-page.html', styleUrl: './tea-status-page.scss', }) export class TeaStatusPage implements OnDestroy { private readonly http = inject(HttpClient); private readonly element = inject>(ElementRef); private requests: Subscription[] = []; private revision = { measures: 0, episodes: 0, patient: 0 }; readonly section = signal
('resumen'); readonly measures = signal([]); readonly alterationTypes = signal([]); readonly reports = signal([]); readonly measureState = signal('inicial'); readonly measureError = signal(''); readonly episodes = signal([]); readonly episodeTotal = signal(0); readonly episodeState = signal('inicial'); readonly episodeError = signal(''); readonly selected = signal(null); readonly patientResources = signal([]); readonly patientState = signal('inicial'); readonly patientError = signal(''); periodo = '2025-S1'; historyPeriods = '2025-01,2025-02,2025-03'; measureId = 'M28-casos-por-estado'; eventCutoff = ''; knowledgeCutoff = ''; page = 0; pageSize = 5; filters = { since: '', cutoff: '', status: '', stage: '', stageFrom: '', stageTo: '', age: '', mchatMin: '', mchatMax: '', cssMin: '', cssMax: '', eeg: '', alteration: '' }; readonly stages = stages; constructor() { this.requests.push(this.http.get('/tea/fhir/Measure').subscribe({ next: bundle => { this.measures.set(resources(bundle).filter(m => /^M(2[1-9]|30)-/.test(m.id))); if (this.alterationsAvailable()) this.requests.push(this.http.get('/tea/fhir/CodeSystem/tea-eeg-metrica').subscribe({ next: system => this.alterationTypes.set(system.concept ?? []), error: () => this.alterationTypes.set([]) })); this.loadSummary(); }, error: () => { this.measureState.set('error'); this.measureError.set('No fue posible cargar los indicadores.'); }, })); } ngOnDestroy() { this.requests.forEach(s => s.unsubscribe()); } changeSection(section: Section) { this.section.set(section); if (section === 'resumen') this.loadSummary(); if (section === 'historico') this.loadHistory(); if (section === 'seguimiento' && this.episodeState() === 'inicial') this.loadEpisodes(); } private cutoffs(params: HttpParams): HttpParams { if (this.eventCutoff) params = params.set('corte_evento', this.eventCutoff); if (this.knowledgeCutoff) params = params.set('corte_conocimiento', new Date(this.knowledgeCutoff).toISOString()); return params; } loadSummary() { const token = ++this.revision.measures; const measures = this.measures(); if (!measures.length) { this.measureState.set('listo'); this.reports.set([]); return; } this.measureState.set('cargando'); const params = this.cutoffs(new HttpParams().set('periodo', this.periodo)); this.requests.push(forkJoin(measures.map(m => this.http.get(`/tea/fhir/Measure/${encodeURIComponent(m.id)}/$evaluate-measure`, { params }))).subscribe({ next: reports => { if (token === this.revision.measures) { this.reports.set(reports); this.measureState.set('listo'); } }, error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } }, })); } loadHistory() { const token = ++this.revision.measures; const measure = this.measures().find(m => m.id === this.measureId); if (!measure) { this.measureState.set('error'); this.measureError.set('Seleccione un indicador disponible.'); return; } this.measureState.set('cargando'); const params = this.cutoffs(new HttpParams().set('measure', measure.url).set('periodo', this.historyPeriods.replace(/\s/g, '')).set('_count', 200)); this.requests.push(this.http.get('/tea/fhir/MeasureReport', { params }).subscribe({ next: bundle => { if (token === this.revision.measures) { const found = resources(bundle); if (bundle.total > found.length) { this.measureError.set('Seleccione como máximo 200 periodos.'); this.measureState.set('error'); return; } this.reports.set(found); this.measureState.set('listo'); } }, error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } }, })); } title(report: Resource) { return this.measures().find(m => report.measure?.split('|')[0] === m.url)?.title ?? report.measure; } rows(report: Resource): { label: string; value: string }[] { const group = report.group?.[0]; if (!group) return []; const rows = (group.population ?? []).map((p: Resource) => ({ label: populations[code(p.code)] ?? text(p.code), value: this.value(p, 'count') })); const measure = this.measures().find(m => report.measure?.split('|')[0] === m.url); if (code(measure?.scoring) !== 'cohort') rows.push({ label: 'Resultado', value: group.measureScore ? this.score(group.measureScore) : 'Sin dato' }); for (const extension of group.measureScore?.extension ?? []) { if (extension.url?.endsWith('/q1') || extension.url?.endsWith('/q3')) rows.push({ label: extension.url.endsWith('/q1') ? 'Primer cuartil' : 'Tercer cuartil', value: `${extension.valueDecimal} días` }); } for (const stratum of group.stratifier?.[0]?.stratum ?? []) { const name = code(stratum.value); const label = stages[name] ?? ({ '16_23': '16 a 23 meses', '24_29': '24 a 29 meses', '30_36': '30 a 36 meses' } as Record)[name] ?? text(stratum.value); if (code(measure?.scoring) === 'cohort') rows.push({ label, value: this.value(stratum.population?.[0], 'count') }); else { for (const p of stratum.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') }); rows.push({ label: `${label} — resultado`, value: stratum.measureScore ? this.score(stratum.measureScore) : 'Sin dato' }); } } for (const extra of report.group?.slice(1) ?? []) { const label = text(extra.code) || 'Grupo'; for (const p of extra.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') }); rows.push({ label: `${label} — resultado`, value: extra.measureScore ? this.score(extra.measureScore) : 'Sin dato' }); } return rows; } value(value: Resource, field: string): string { if (value?.[`_${field}`]?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido'; return value?.[field] == null ? 'Sin dato' : String(value[field]); } score(score: Resource): string { if (score?._value?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido'; if (score?.value == null) return 'Sin dato'; return score.unit === 'd' ? `${score.value} días` : `${(100 * score.value).toFixed(1)} %`; } private errorText(error: Resource) { return error?.error?.issue?.[0]?.diagnostics ?? 'No fue posible consultar la información. Intente de nuevo.'; } applyFilters() { this.page = 0; this.loadEpisodes(); } loadEpisodes() { const token = ++this.revision.episodes; this.episodeState.set('cargando'); let p = new HttpParams().set('_count', this.pageSize).set('_offset', this.page * this.pageSize).set('_include', '*'); const f = this.filters; for (const [key, val] of [['status', f.status], ['etapa', f.stage], ['grupo-edad', f.age], ['resultado-eeg', f.eeg]] as const) if (val) p = p.set(key, val); if (this.alterationsAvailable() && f.alteration) p = p.set('alteracion', f.alteration); for (const [key, prefix, val] of [['date', 'ge', f.since], ['date', 'le', f.cutoff], ['fecha-etapa', 'ge', f.stageFrom], ['fecha-etapa', 'le', f.stageTo], ['mchat', 'ge', f.mchatMin], ['mchat', 'le', f.mchatMax], ['css', 'ge', f.cssMin], ['css', 'le', f.cssMax]] as const) if (val != null && val !== '') p = p.append(key, prefix + val); this.requests.push(this.http.get('/tea/fhir/EpisodeOfCare', { params: p }).subscribe({ next: bundle => { if (token !== this.revision.episodes) return; const found = resources(bundle); if (found.some(r => !simulated(r))) { this.episodeError.set('La información recibida no está identificada como datos simulados.'); this.episodeState.set('error'); return; } this.episodes.set(found.filter(r => r.resourceType === 'EpisodeOfCare')); this.episodeTotal.set(bundle.total ?? 0); this.episodeState.set('listo'); }, error: e => { if (token === this.revision.episodes) { this.episodeError.set(this.errorText(e)); this.episodeState.set('error'); } }, })); } stage(e: Resource) { const value = code(e.type?.[0]); return stages[value] ?? value ?? 'Sin dato'; } stageDate(e: Resource) { return e.extension?.find((x: Resource) => x.url.endsWith('/fecha-etapa'))?.valueDate ?? 'Sin dato'; } patientId(e: Resource): string { return e.patient?.reference?.startsWith('Patient/') ? e.patient.reference.slice(8) : ''; } openPatient(e: Resource) { const id = this.patientId(e); if (!id) { this.episodeError.set('El episodio no identifica a un paciente.'); this.episodeState.set('error'); return; } const token = ++this.revision.patient; this.selected.set(id); this.patientState.set('cargando'); this.patientResources.set([]); this.requests.push(this.http.get(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`).subscribe({ next: bundle => { if (token !== this.revision.patient || this.selected() !== id) return; const found = resources(bundle); if (!found.some(r => r.resourceType === 'Patient' && r.id === id) || found.some(r => !simulated(r) || (r.resourceType === 'Patient' && r.id !== id) || (r.subject?.reference && r.subject.reference !== `Patient/${id}`))) { this.patientError.set('No se pudo verificar la identidad o el origen de la ficha.'); this.patientState.set('error'); return; } this.patientResources.set(found); this.patientState.set('listo'); }, error: e => { if (token === this.revision.patient && this.selected() === id) { this.patientError.set(this.errorText(e)); this.patientState.set('error'); } }, })); } back() { const id = this.selected(); ++this.revision.patient; this.selected.set(null); setTimeout(() => this.element.nativeElement.querySelector(`[data-patient="${id}"]`)?.focus()); } ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); } eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); } eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : quality === 'SIN_ANALIZAR' ? 'Sin analizar' : 'Sin dato'; } eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; } // The EEG analysis's checks: A is out of range, N within. qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'N' ? 'dentro de rango' : value === 'A' ? 'fuera de rango' : 'sin dato'; } quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && r.code?.coding?.[0]?.system === 'urn:tea:validation'); } electrode(o: Resource): string | undefined { return o.component?.find((c: Resource) => c.code?.text === 'electrode')?.valueString; } alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); } alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); } componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); } observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim() : o.valueString ?? 'Sin dato'); } }