import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { forkJoin, map, Observable, of, shareReplay } from 'rxjs'; import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir'; import { estratoValor } from './indicadores-fhir'; import { SeguimientoQuery } from './cacu-seguimiento.models'; import { validSeguimientoQuery } from './cacu-seguimiento.service'; import { CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService, } from './tea-seguimiento.service'; // TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an // `EpisodeOfCare` with its resources included, and `Patient//$resumen-tea` is the summary. Both are mapped into the // shapes the page already reads, and checked by the same rules. interface Observation extends Resource { code?: Concept; effectiveDateTime?: string; subject?: { reference?: string }; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; interpretation?: Concept[]; dataAbsentReason?: Concept; referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[]; component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueBoolean?: boolean; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[]; } interface Report extends Resource { effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[]; } interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] } interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] } const MAX_COUNT = 200; const METRICAS = 'tea-eeg-metrica'; // The EEG analysis's quality checks, under the code system of its own validation report. const CRITERIOS = 'urn:tea:validation'; const FILTRO_EEG: Record = { sin_eeg_valido: 'sin-eeg-valido' }; const INTERPRETACION: Record = { H: 'aumentado', L: 'disminuido', N: 'normal' }; // The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average, // the scalp zones of the EEG analysis (`tea.contracts.ZONES`). export const ELECTRODOS: Record = { Fp1: [-.25, .77], Fp2: [.25, .77], F7: [-.65, .47], F3: [-.33, .4], Fz: [0, .38], F4: [.33, .4], F8: [.65, .47], T3: [-.8, 0], C3: [-.4, 0], Cz: [0, 0], C4: [.4, 0], T4: [.8, 0], T5: [-.65, -.47], P3: [-.33, -.4], Pz: [0, -.38], P4: [.33, -.4], T6: [.65, -.47], O1: [-.25, -.77], O2: [.25, -.77], }; const REGIONES: [string, string, string[]][] = [ ['frontal_izq', 'Frontal izquierda', ['Fp1', 'F3', 'F7']], ['frontal_der', 'Frontal derecha', ['Fp2', 'F4', 'F8']], ['frontal_media', 'Frontal media', ['Fz']], ['central', 'Central', ['C3', 'Cz', 'C4']], ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']], ['temporal_der', 'Temporal derecha', ['T4', 'T6']], ['parietal', 'Parietal', ['P3', 'Pz', 'P4']], ['occipital', 'Occipital', ['O1', 'O2']], ]; const EJE = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100); // How far from a measured electrode the map still shows a value; beyond it, no electrode speaks for the scalp. const ALCANCE = .45; const round2 = (value: number) => Math.round(value * 100) / 100; export const grupoEdad = (codigo: string | undefined) => !codigo ? '' : codigo === 'sin_dato' ? 'Sin dato' : `${estratoValor(codigo)} meses`; const grupoCodigo = (etiqueta: string) => etiqueta.replace(' meses', '').replace('-', '_'); function byCode(observations: Observation[], wanted: string): Observation | undefined { return observations.find(o => code(o.code) === wanted); } function component(o: Observation | undefined, wanted: string) { return o?.component?.find(c => code(c.code) === wanted); } // The map of one metric's electrode z-scores: inverse-distance weights within reach of a measured electrode. export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Record): TeaEegMapa { const puntos = Object.entries(valores).filter(([nombre]) => ELECTRODOS[nombre]).map(([nombre, z]) => ({ xy: ELECTRODOS[nombre], z })); const z = EJE.map(y => EJE.map(x => { let peso = 0, suma = 0; for (const p of puntos) { const d2 = (x - p.xy[0]) ** 2 + (y - p.xy[1]) ** 2; if (d2 < 1e-9) return round2(p.z); if (d2 > ALCANCE ** 2) continue; peso += 1 / d2; suma += p.z / d2; } return peso ? round2(suma / peso) : null; })); const regiones = REGIONES.flatMap(([c, e, nombres]) => { const medidos = nombres.filter(n => typeof valores[n] === 'number'); return medidos.length ? [{ codigo: c, etiqueta: e, valor_z: round2(medidos.reduce((s, n) => s + valores[n], 0) / medidos.length) }] : []; }).sort((a, b) => Math.abs(b.valor_z) - Math.abs(a.valor_z)); return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones }; } // The module as the page writes it: `MODULO_1` is 1, the toddler module is T. function moduloAdos2(codigo: string | undefined): string | undefined { const modulo = codigo?.replace(/^ados2\.modulo\./, ''); return modulo === 'TODDLER' ? 'T' : modulo?.replace(/^MODULO_/, ''); } export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null { const css = component(o, 'ados2.css')?.valueInteger; if (!o?.effectiveDateTime || typeof css !== 'number') return null; const modulo = moduloAdos2(code(component(o, 'ados2.modulo')?.valueCodeableConcept)) ?? ''; const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase(); const items = (o.component ?? []).filter(c => extension(c, 'dominio')); const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => { const codigo = code(c.code)!; const reactivos = items.filter(i => extension(i, 'dominio')?.valueCode === codigo).map(i => ({ codigo: (code(i.code) ?? '').split('_').pop()!.toUpperCase(), etiqueta: display(i.code) ?? '', puntaje: i.valueInteger ?? 0, puntaje_algoritmo: extension(i, 'puntaje-algoritmo')?.valueInteger ?? 0, })); return { codigo, etiqueta: display(c.code) ?? codigo, puntaje: c.valueInteger ?? 0, maximo: 2 * reactivos.length, reactivos }; }); return { fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '', dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0), clasificacion: clasificacion && Object.hasOwn(CLASIFICACIONES_ADOS2, clasificacion) ? clasificacion as TeaAdos2['clasificacion'] : null, css, nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'], }; } // The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR // extension holds scalars, not arrays. function curvaDe(o: Observation): TeaCurvaReferencia | null { const curva = extension(o, 'curva-referencia'); if (!curva) return null; const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number'); return { fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '', edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'), }; } // A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't // cover the child's age (or none is in production yet). function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion { const codigo = code(o.code) ?? ''; const metrica = metricas.find(m => m.code === codigo); const valor = o.valueQuantity?.value ?? null; const z = component(o, 'z')?.valueQuantity?.value; const evaluable = valor !== null && typeof z === 'number'; const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable'; const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value; const referencia = typeof low === 'number' && typeof high === 'number' ? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null; const curva = evaluable ? curvaDe(o) : null; return { codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo, unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '', referencia: evaluable ? referencia : null, valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado, sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia', efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean), ...(curva ? { curva_referencia: curva } : {}), }; } // One quality check as the EEG analysis reports it: its value or reason, A/N, the bad channel's electrode, whether it // alone invalidates the EEG. function criterio(o: Observation): TeaCriterioCalidad { const parte = (nombre: string) => o.component?.find(c => c.code?.text === nombre); return { codigo: codeIn(o.code, CRITERIOS)!, etiqueta: display(o.code) ?? codeIn(o.code, CRITERIOS)!, valor: o.valueQuantity?.value ?? o.valueString ?? null, unidad: o.valueQuantity?.unit ?? '', nivel: code(o.interpretation?.[0]) === 'A' ? 'malo' : 'bueno', electrodo: parte('electrode')?.valueString ?? null, decisivo: parte('decisive')?.valueBoolean === true, }; } // The study EEG of `report`, with the observations it lists and the electrode maps of its metrics. export function eegDeReporte(report: Report | undefined, observations: Observation[], metricas: Metric[]): TeaEeg | null { if (!report?.effectiveDateTime) return null; const ids = new Set((report.result ?? []).map(r => referenceId(r))); const listed = observations.filter(o => ids.has(o.id)); const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad; const duracion = extension(report, 'duracion-min')?.valueDecimal; const edad = extension(report, 'edad-meses')?.valueDecimal; // The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards. const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas)); // A metric's electrode values are `electrodos-`. const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length))) .map(o => { const valores = Object.fromEntries((o.component ?? []).map(c => [code(c.code), c.valueQuantity?.value]) .filter((e): e is [string, number] => !!e[0] && typeof e[1] === 'number')); return mapaDeElectrodos(code(o.code)!, display(o.code) ?? code(o.code)!, valores); }) .filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable')); return { fecha: report.effectiveDateTime.slice(0, 10), duracion_min: duracion === undefined ? null : Math.round(duracion), canales: extension(report, 'canales')?.valueInteger ?? null, ...(typeof edad === 'number' ? { edad_meses: edad } : {}), calidad: calidad(report.conclusionCode?.[0]), criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio), alteraciones, mapas, ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) }, }; } // The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and // probabilities. A row missing a number the panel needs is left out; without rows there is no panel. export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null { if (!riesgo) return null; const nivel = extension(riesgo, 'modelo-nivel')?.valueString; const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => { const numero = (nombre: string) => extension(p, nombre)?.valueDecimal; const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding; const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString; const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal, numero('probabilidad-referencia')]; if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome) || !valores.every(v => typeof v === 'number')) return null; const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[]; return { biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z, tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null, }; }).filter((f): f is TeaRelacionAdos2 => f !== null); if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null; return { validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel, n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0, version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas, }; } function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null { if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null; return alteracionesDe(report, observations).length ? 'anormal' : 'normal'; } function alteracionesDe(report: Report | undefined, observations: Observation[]): string[] { const ids = new Set((report?.result ?? []).map(r => referenceId(r))); return observations.filter(o => ids.has(o.id) && codeIn(o.code, METRICAS) && ['H', 'L'].includes(code(o.interpretation?.[0]) ?? '')) .map(o => code(o.code)!); } // One row of the list: the episode and what the search included for its patient. export function pacienteDeEpisodio(episode: Resource, included: Resource[], validadas: boolean): TeaSeguimientoPaciente { const id = episode.id!; const own = included.filter(r => referenceId((r['subject'] ?? r['patient']) as { reference?: string }) === id); const observations = own.filter(r => r.resourceType === 'Observation') as Observation[]; const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined; const ados2 = byCode(observations, 'ados2'); const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined; const modulo = moduloAdos2(code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)); return { id_seudonimo: id, grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code), ultimo_eeg: report?.effectiveDateTime?.slice(0, 10) ?? null, mchat: byCode(observations, 'mchat.puntaje')?.valueInteger ?? null, css_ados2: component(ados2, 'ados2.css')?.valueInteger ?? null, alteraciones_eeg: resultadoEeg(report, observations, validadas), modulo_ados2: modulo ?? null, estado_caso: episode['status'] === 'finished' ? 'completo' : 'en_proceso', pendientes: (plan?.activity ?? []).filter(a => a.detail?.status !== 'completed').map(a => a.detail?.code?.text ?? display(a.detail?.code) ?? ''), alteraciones: validadas ? alteracionesDe(report, observations) : [], }; } function parameter(p: Resource | undefined, name: string): number { const found = (p?.['parameter'] as { name: string; valueInteger?: number }[] | undefined)?.find(x => x.name === name); return found?.valueInteger ?? 0; } function porAlteracion(p: Resource | undefined, metricas: Metric[]) { return ((p?.['parameter'] ?? []) as { name: string; part?: { name: string; valueCode?: string; valueInteger?: number }[] }[]) .filter(x => x.name === 'por_alteracion').map(x => { const codigo = x.part?.find(y => y.name === 'alteracion')?.valueCode ?? ''; return { codigo, etiqueta: metricas.find(m => m.code === codigo)?.display ?? codigo, n: x.part?.find(y => y.name === 'pacientes')?.valueInteger ?? 0 }; }); } function isoDay(date: Date) { return date.toISOString().slice(0, 10); } // From `meses` before the cut-off (plus a day) to the cut-off, as CaCu's list. export function ventana(corte: string, meses: number): { desde: string; hasta: string } { const [y, m, d] = corte.split('-').map(Number); const total = y * 12 + m - 1 - meses; const year = Math.floor(total / 12), month = total % 12; const last = new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); const desde = new Date(Date.UTC(year, month, Math.min(d, last) + 1)); return { desde: isoDay(desde), hasta: corte }; } @Injectable() export class FhirTeaSeguimientoService extends TeaSeguimientoService { private readonly client = inject(HttpClient); private metricas$?: Observable; today = () => new Date(); private metricas(): Observable { this.metricas$ ??= this.client.get<{ concept?: Metric[] }>(`/tea/fhir/CodeSystem/${METRICAS}`).pipe( map(system => system.concept ?? []), shareReplay({ bufferSize: 1, refCount: false })); return this.metricas$; } override consultar(query: SeguimientoQuery) { if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos'); const corte = query.corte ?? isoDay(this.today()); const { desde, hasta } = ventana(corte, query.meses); let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta); if (query.estatus) params = params.set('resultado-eeg', FILTRO_EEG[query.estatus] ?? query.estatus); if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad)); const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css); if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max); if (css) params = params.append('css', 'ge' + css.min).append('css', 'le' + css.max); if (query.estado_caso) params = params.set('status', query.estado_caso === 'completo' ? 'finished' : 'active'); if (query.alteracion) params = params.set('alteracion', query.alteracion); const page = params.set('_count', Math.min(query.page_size, MAX_COUNT)).set('_offset', (query.page - 1) * query.page_size).set('_include', '*'); // The list has no children out of the protocol any more: the screening ends with a good EEG. const empty = query.estado_caso === 'fuera_protocolo'; return forkJoin({ bundle: empty ? of({ resourceType: 'Bundle', total: 0, entry: [] }) : this.client.get('/tea/fhir/EpisodeOfCare', { params: page }), resumen: this.client.get('/tea/fhir/EpisodeOfCare/$resumen-eeg', { params }), metricas: this.metricas(), }).pipe(map(({ bundle, resumen, metricas }) => { const validadas = (resumen['parameter'] as { name: string }[] | undefined)?.some(p => p.name === 'normales') ?? false; const episodes = (bundle.entry ?? []).filter(e => e.search?.mode !== 'include' && e.resource.resourceType === 'EpisodeOfCare').map(e => e.resource); const included = (bundle.entry ?? []).filter(e => e.search?.mode === 'include').map(e => e.resource); const total = empty ? 0 : bundle.total ?? episodes.length; return teaSeguimientoResponse({ simulado: episodes.every(isSimulated), corte, ventana: { meses: query.meses, desde, hasta }, filtros: { alteraciones_eeg: query.estatus ?? null }, paginacion: { page: query.page, page_size: query.page_size, total_items: total, total_pages: Math.ceil(total / query.page_size) }, items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)), tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [], resumen_eeg: { validadas, con_eeg_valido: validadas ? parameter(resumen, 'normales') + parameter(resumen, 'anormales') : parameter(resumen, 'con_eeg_valido'), normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'), por_alteracion: porAlteracion(resumen, metricas), }, }); })); } override detalle(id: string) { return forkJoin({ bundle: this.client.get(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`), metricas: this.metricas(), }).pipe(map(({ bundle, metricas }) => { const all = resources(bundle); const observations = all.filter(r => r.resourceType === 'Observation') as Observation[]; const episode = resources(bundle, 'EpisodeOfCare')[0]; const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]); return teaPacienteDetalle({ simulado: all.length > 0 && all.every(isSimulated), id_seudonimo: id, grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code), ados2: ados2DeObservacion(byCode(observations, 'ados2')), eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas), ...(relacion ? { relacion_ados2: relacion } : {}), }, id); })); } }