Connect TEA screening views to FHIR
This commit is contained in:
@@ -1,53 +1,185 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Component, inject, signal } from '@angular/core';
|
||||
import { Component, ElementRef, inject, OnDestroy, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { forkJoin, Subscription } from 'rxjs';
|
||||
|
||||
interface Population { count?: number }
|
||||
interface Stratum { value?: { coding?: { code?: string; display?: string }[] }; population?: Population[] }
|
||||
interface Report { group?: { population?: Population[]; stratifier?: { stratum?: Stratum[] }[] }[] }
|
||||
type Resource = any;
|
||||
type Section = 'resumen' | 'historico' | 'seguimiento';
|
||||
type State = 'inicial' | 'cargando' | 'listo' | 'error';
|
||||
const stages: Record<string, string> = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' };
|
||||
const populations: Record<string, string> = { '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],
|
||||
template: `
|
||||
<h1>Casos por estatus</h1>
|
||||
<p>Consulte la etapa alcanzada por las niñas y los niños en el periodo seleccionado.</p>
|
||||
<form (ngSubmit)="consultar()">
|
||||
<label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1" /></label>
|
||||
<button type="submit" [disabled]="estado() === 'cargando'">Consultar</button>
|
||||
</form>
|
||||
@if (estado() === 'cargando') { <p role="status">Consultando información…</p> }
|
||||
@if (estado() === 'error') { <p role="alert">No fue posible consultar el periodo. Verifique el periodo e intente de nuevo.</p> }
|
||||
@if (estado() === 'listo') {
|
||||
<p>Total: {{ total() }}</p>
|
||||
@if (filas().length === 0) { <p>No hay casos para este periodo.</p> }
|
||||
@else { <ul>@for (fila of filas(); track fila.codigo) { <li>{{ fila.nombre }}: {{ fila.cantidad }}</li> }</ul> }
|
||||
}
|
||||
`,
|
||||
imports: [FormsModule, RouterLink],
|
||||
templateUrl: './tea-status-page.html',
|
||||
styleUrl: './tea-status-page.scss',
|
||||
})
|
||||
export class TeaStatusPage {
|
||||
export class TeaStatusPage implements OnDestroy {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly element = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
private requests: Subscription[] = [];
|
||||
private revision = { measures: 0, episodes: 0, patient: 0 };
|
||||
readonly section = signal<Section>('resumen');
|
||||
readonly measures = signal<Resource[]>([]);
|
||||
readonly alterationTypes = signal<Resource[]>([]);
|
||||
readonly reports = signal<Resource[]>([]);
|
||||
readonly measureState = signal<State>('inicial');
|
||||
readonly measureError = signal('');
|
||||
readonly episodes = signal<Resource[]>([]);
|
||||
readonly episodeTotal = signal(0);
|
||||
readonly episodeState = signal<State>('inicial');
|
||||
readonly episodeError = signal('');
|
||||
readonly selected = signal<string | null>(null);
|
||||
readonly patientResources = signal<Resource[]>([]);
|
||||
readonly patientState = signal<State>('inicial');
|
||||
readonly patientError = signal('');
|
||||
periodo = '2025-S1';
|
||||
readonly estado = signal<'inicial' | 'cargando' | 'listo' | 'error'>('inicial');
|
||||
readonly total = signal(0);
|
||||
readonly filas = signal<{ codigo: string; nombre: string; cantidad: number }[]>([]);
|
||||
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;
|
||||
|
||||
consultar() {
|
||||
this.estado.set('cargando');
|
||||
this.http.get<Report>('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure', {
|
||||
params: new HttpParams().set('periodo', this.periodo),
|
||||
}).subscribe({
|
||||
next: report => {
|
||||
const group = report.group?.[0];
|
||||
this.total.set(group?.population?.[0]?.count ?? 0);
|
||||
const nombres: Record<string, string> = { SOLO_MCHAT: 'M-CHAT', PSICOLOGIA: 'Psicología', NEUROPEDIATRIA: 'Neuropediatría', EEG: 'EEG' };
|
||||
this.filas.set((group?.stratifier?.[0]?.stratum ?? []).map(s => {
|
||||
const codigo = s.value?.coding?.[0]?.code ?? '';
|
||||
return { codigo, nombre: nombres[codigo] ?? s.value?.coding?.[0]?.display ?? codigo, cantidad: s.population?.[0]?.count ?? 0 };
|
||||
}));
|
||||
this.estado.set('listo');
|
||||
constructor() {
|
||||
this.requests.push(this.http.get<Resource>('/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<Resource>('/tea/fhir/CodeSystem/tea-eeg-metrica').subscribe({ next: system => this.alterationTypes.set(system.concept ?? []), error: () => this.alterationTypes.set([]) }));
|
||||
this.loadSummary();
|
||||
},
|
||||
error: () => this.estado.set('error'),
|
||||
});
|
||||
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<Resource>(`/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<Resource>('/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<string, string>)[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<Resource>('/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<Resource>(`/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<HTMLButtonElement>(`[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' : 'Sin dato'; }
|
||||
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
|
||||
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : '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}`) && code(r.code).startsWith('eeg.calidad_')); }
|
||||
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 ?? ''}` : 'Sin dato'); }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user