efe4404c4e
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas 5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
248 lines
17 KiB
TypeScript
248 lines
17 KiB
TypeScript
import { inject, Injectable } from '@angular/core';
|
||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||
import { map } from 'rxjs';
|
||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||
|
||
// The EEG filter: by alteration once the domain expert has validated them, otherwise only by a valid EEG or none.
|
||
export type AlteracionesEeg = 'normal' | 'anormal' | 'valido' | 'sin_eeg_valido';
|
||
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
|
||
export interface TeaSeguimientoPaciente {
|
||
id_seudonimo: string;
|
||
grupo_edad: string;
|
||
ultimo_eeg: string | null;
|
||
mchat: number | null;
|
||
css_ados2: number | null;
|
||
alteraciones_eeg: 'normal' | 'anormal' | null;
|
||
modulo_ados2: string | null;
|
||
estado_caso: EstadoCaso;
|
||
// What a case in process still lacks.
|
||
pendientes: string[];
|
||
// Codes of the alterations found.
|
||
alteraciones: string[];
|
||
}
|
||
export interface TeaResumenEeg {
|
||
// Without validated alterations only the split by a valid EEG is known: `normales`, `anormales` and `por_alteracion`
|
||
// stay empty.
|
||
validadas: boolean; con_eeg_valido: number;
|
||
normales: number; anormales: number; sin_eeg: number;
|
||
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
|
||
}
|
||
export interface TeaSeguimientoResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
|
||
filtros: { alteraciones_eeg: AlteracionesEeg | null };
|
||
items: TeaSeguimientoPaciente[];
|
||
tipos_alteracion: { codigo: string; etiqueta: string }[];
|
||
// Of every patient that matches the filters, not only this page's.
|
||
resumen_eeg: TeaResumenEeg;
|
||
}
|
||
export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: number; puntaje_algoritmo: number }
|
||
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
|
||
export interface TeaAdos2 {
|
||
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
|
||
clasificacion: ClasificacionAdos2 | null; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||
}
|
||
export type ClasificacionAdos2 = 'autismo' | 'espectro_autista' | 'no_espectro' | 'preocupacion_leve_moderada' | 'preocupacion_severa';
|
||
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||
// EEG metrics against age baselines and their associated effects, both pending medical validation.
|
||
export type TeaNivelCalidad = 'bueno' | 'malo' | 'sin_analizar';
|
||
// One quality check of the EEG analysis: a study-wide rule, or a bad channel with its electrode and reason.
|
||
export interface TeaCriterioCalidad {
|
||
codigo: string; etiqueta: string; valor: number | string | null; unidad: string; nivel: 'bueno' | 'malo';
|
||
electrodo: string | null; decisivo: boolean;
|
||
}
|
||
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
|
||
export interface TeaEegAlteracion {
|
||
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number; mediana: number | null } | null;
|
||
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
|
||
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
|
||
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
|
||
// The age norm the reference comes from (percentiles by month), when the analysis sends it.
|
||
curva_referencia?: TeaCurvaReferencia | null;
|
||
}
|
||
export interface TeaCurvaReferencia {
|
||
fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[];
|
||
}
|
||
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
|
||
export interface TeaEeg {
|
||
fecha: string; duracion_min: number | null; canales: number | null;
|
||
// Age at the EEG, to place the patient on the age norms.
|
||
edad_meses?: number | null;
|
||
// The overall rating is the EEG analysis's verdict; its checks say why.
|
||
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
|
||
alteraciones: TeaEegAlteracion[];
|
||
// One map per alteration that could be evaluated, on shared axes.
|
||
mapas: TeaEegMapa[];
|
||
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
|
||
}
|
||
// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for
|
||
// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation.
|
||
export interface TeaRelacionAdos2 {
|
||
biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number;
|
||
tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string;
|
||
or: number; ic_inf: number; ic_sup: number; q: number;
|
||
probabilidad: number; probabilidad_referencia: number; observado: number | null;
|
||
}
|
||
export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] }
|
||
export interface TeaPacienteDetalle {
|
||
simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null;
|
||
// Absent until the WebApi serves the model.
|
||
relacion_ados2?: TeaRelacionModelo | null;
|
||
}
|
||
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
|
||
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
|
||
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
|
||
preocupacion_leve_moderada: 'Preocupación leve a moderada', preocupacion_severa: 'Preocupación de moderada a severa',
|
||
};
|
||
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
|
||
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
|
||
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
|
||
export const RANGOS_MCHAT = [
|
||
{ codigo: 'bajo', etiqueta: 'Riesgo bajo (0–2)', min: 0, max: 2 },
|
||
{ codigo: 'medio', etiqueta: 'Riesgo medio (3–7)', min: 3, max: 7 },
|
||
{ codigo: 'alto', etiqueta: 'Riesgo alto (8–20)', min: 8, max: 20 },
|
||
];
|
||
export const RANGOS_CSS = [
|
||
{ codigo: 'minimo', etiqueta: 'Evidencia mínima o nula (1–2)', min: 1, max: 2 },
|
||
{ codigo: 'bajo', etiqueta: 'Nivel bajo (3–4)', min: 3, max: 4 },
|
||
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
|
||
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
|
||
];
|
||
export const ALTERACIONES_EEG: SeguimientoStatus[] = [
|
||
{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' },
|
||
];
|
||
export const EEG_VALIDO: SeguimientoStatus[] = [{ codigo: 'valido', etiqueta: 'Con EEG válido' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' }];
|
||
|
||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
|
||
const filtroEeg = (v: unknown) => v === null || ['normal', 'anormal', 'valido', 'sin_eeg_valido'].includes(v as string);
|
||
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
|
||
// ADOS-2 item codes: 0 to 3, and 7 to 9 for an item that doesn't apply or wasn't scored.
|
||
const CODIGOS_REACTIVO = [0, 1, 2, 3, 7, 8, 9];
|
||
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
|
||
function validResumenEeg(r: unknown): boolean {
|
||
return record(r) && typeof r['validadas'] === 'boolean' && integer(r['con_eeg_valido'])
|
||
&& integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
|
||
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
|
||
}
|
||
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
|
||
// Same rule as CaCu: demonstration records only.
|
||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
|
||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||
|| !record(filters) || !filtroEeg(filters['alteraciones_eeg'])
|
||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
|
||
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
|
||
&& (item['ultimo_eeg'] === null || isoDate(item['ultimo_eeg']))
|
||
&& score(item['mchat'], 0, 20) && score(item['css_ados2'], 1, 10)
|
||
&& eeg(item['alteraciones_eeg']) && (item['modulo_ados2'] === null || typeof item['modulo_ados2'] === 'string')
|
||
&& Object.hasOwn(ESTADOS_CASO, item['estado_caso'] as string) && textos(item['pendientes']) && textos(item['alteraciones']))
|
||
|| !Array.isArray(v['tipos_alteracion']) || !v['tipos_alteracion'].every(t => record(t) && typeof t['codigo'] === 'string' && typeof t['etiqueta'] === 'string')
|
||
|| !validResumenEeg(v['resumen_eeg']))
|
||
throw new Error('Respuesta de seguimiento inválida');
|
||
return v as unknown as TeaSeguimientoResponse;
|
||
}
|
||
|
||
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
|
||
function validAdos(a: unknown): boolean {
|
||
if (a === null) return true;
|
||
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || typeof a['algoritmo'] !== 'string' || !score(a['css'], 1, 10)
|
||
|| !(a['clasificacion'] === null || Object.hasOwn(CLASIFICACIONES_ADOS2, a['clasificacion'] as string))
|
||
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
|
||
// Items carry an ADOS-2 code (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||
const dominios = a['dominios'] as unknown[];
|
||
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
|
||
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && CODIGOS_REACTIVO.includes(r['puntaje'] as number) && score(r['puntaje_algoritmo'], 0, 2))
|
||
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
|
||
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
|
||
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||
}
|
||
// An age norm: ages in increasing order and, at each one, percentiles that never cross.
|
||
const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const;
|
||
function validCurva(c: unknown): boolean {
|
||
if (c === undefined || c === null) return true;
|
||
if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false;
|
||
const edades = c['edad_meses'] as unknown[], n = edades.length;
|
||
if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false;
|
||
const series = PERCENTILES.map(k => c[k]);
|
||
return series.every(s => Array.isArray(s) && s.length === n && s.every(finite))
|
||
&& edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i]));
|
||
}
|
||
// A metric that can't be evaluated says why and has no z; one that can has its value, z and reference.
|
||
function validAlteracion(a: unknown): boolean {
|
||
const ref = a !== null && record(a) ? a['referencia'] : undefined;
|
||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|
||
|| !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
|
||
&& (ref['mediana'] === null || finite(ref['mediana'])))
|
||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false;
|
||
const estado = a['estado'];
|
||
if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
|
||
&& (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
|
||
return finite(a['valor']) && finite(a['valor_z']) && ref !== null && a['sin_evaluar'] === null
|
||
&& ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||
}
|
||
function validEeg(e: unknown): boolean {
|
||
if (e === null) return true;
|
||
const optional = (v: unknown) => v === null || integer(v);
|
||
const edad = record(e) ? e['edad_meses'] : undefined;
|
||
if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
|
||
|| !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0)
|
||
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|
||
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
|
||
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
|
||
&& (c['electrodo'] === null || text(c['electrodo'])) && (c['valor'] === null || finite(c['valor']) || text(c['valor'])))) return false;
|
||
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
|
||
const ejes = e['ejes_mapa'];
|
||
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
|
||
const x = ejes['x'], y = ejes['y'];
|
||
return x.every(finite) && y.every(finite)
|
||
&& Array.isArray(ejes['electrodos']) && ejes['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y']))
|
||
&& e['mapas'].every(m => record(m) && text(m['codigo']) && text(m['metrica']) && Array.isArray(m['z']) && m['z'].length === y.length
|
||
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
|
||
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
|
||
}
|
||
const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1;
|
||
function validRelacion(r: unknown): boolean {
|
||
if (r === undefined || r === null) return true;
|
||
return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string)
|
||
&& integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas'])
|
||
&& r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z'])
|
||
&& ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento'])
|
||
&& finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number)
|
||
&& probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia'])
|
||
&& (f['observado'] === null || finite(f['observado'])));
|
||
}
|
||
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
|
||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])
|
||
|| !validRelacion(v['relacion_ados2']))
|
||
throw new Error('Resumen del paciente inválido');
|
||
return v as unknown as TeaPacienteDetalle;
|
||
}
|
||
|
||
@Injectable({ providedIn: 'root' })
|
||
export class TeaSeguimientoService {
|
||
private readonly http = inject(HttpClient);
|
||
// `estatus` carries the EEG filter so the shared form and query work for both domains.
|
||
consultar(query: SeguimientoQuery) {
|
||
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||
if (query.corte) params = params.set('corte', query.corte);
|
||
if (query.estatus) params = params.set('alteraciones_eeg', query.estatus);
|
||
if (query.grupo_edad) params = params.set('grupo_edad', 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.set('mchat_min', mchat.min).set('mchat_max', mchat.max);
|
||
if (css) params = params.set('css_min', css.min).set('css_max', css.max);
|
||
if (query.estado_caso) params = params.set('estado_caso', query.estado_caso);
|
||
if (query.alteracion) params = params.set('alteracion', query.alteracion);
|
||
return this.http.get<unknown>('/tea/seguimiento', { params }).pipe(map(teaSeguimientoResponse));
|
||
}
|
||
detalle(id: string) {
|
||
return this.http.get<unknown>(`/tea/seguimiento/${encodeURIComponent(id)}`).pipe(map(v => teaPacienteDetalle(v, id)));
|
||
}
|
||
}
|