feat(tea): seguimiento con resumen por paciente y resumen por periodo
- Pestaña Seguimiento de TEA: tabla de pacientes con filtro de alteraciones EEG y fila desplegable con ADOS-2 por reactivo, calidad del EEG y mapa topográfico (GET /tea/seguimiento/<id>). - Indicadores destacados: M21 y M22 (pacientes con TEA con y sin EEG). - Con un solo periodo elegido, TEA muestra un párrafo de resumen en lugar de las tarjetas.
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
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';
|
||||
|
||||
export type AlteracionesEeg = 'normal' | 'anormal';
|
||||
export interface TeaSeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
grupo_edad: string;
|
||||
ultimo_eeg: string | null;
|
||||
mchat: number | null;
|
||||
css_ados2: number | null;
|
||||
alteraciones_eeg: AlteracionesEeg | null;
|
||||
}
|
||||
export interface TeaSeguimientoResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
|
||||
filtros: { alteraciones_eeg: AlteracionesEeg | null };
|
||||
items: TeaSeguimientoPaciente[];
|
||||
}
|
||||
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: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
}
|
||||
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||||
export interface TeaEeg {
|
||||
fecha: string; duracion_min: number; canales: number; canales_rechazados: number; segmentos_utiles_pct: number; impedancia_max_kohm: number;
|
||||
artefactos_pct: { parpadeo: number; movimiento: number; muscular: number }; puntaje_calidad: number; calidad: 'buena' | 'aceptable' | 'deficiente';
|
||||
regiones: TeaEegRegion[];
|
||||
mapa: { metrica: string; x: number[]; y: number[]; z: (number | null)[][]; electrodos: { nombre: string; x: number; y: number }[] };
|
||||
}
|
||||
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
|
||||
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
|
||||
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
|
||||
|
||||
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 score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
|
||||
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) || !eeg(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'])))
|
||||
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 pct = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 100;
|
||||
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']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|
||||
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
|
||||
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
|
||||
// Items score 0–3 (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']) && score(r['puntaje'], 0, 3) && 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);
|
||||
}
|
||||
function validEeg(e: unknown): boolean {
|
||||
if (e === null) return true;
|
||||
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !integer(e['canales_rechazados'])
|
||||
|| (e['canales_rechazados'] as number) > (e['canales'] as number) || !pct(e['segmentos_utiles_pct']) || !finite(e['impedancia_max_kohm'])
|
||||
|| !pct(e['puntaje_calidad']) || !['buena', 'aceptable', 'deficiente'].includes(e['calidad'] as string)) return false;
|
||||
const art = e['artefactos_pct'], mapa = e['mapa'];
|
||||
if (!record(art) || !['parpadeo', 'movimiento', 'muscular'].every(k => pct(art[k]))) return false;
|
||||
if (!Array.isArray(e['regiones']) || !e['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))) return false;
|
||||
if (!record(mapa) || !text(mapa['metrica']) || !Array.isArray(mapa['x']) || !Array.isArray(mapa['y']) || !Array.isArray(mapa['z'])) return false;
|
||||
const x = mapa['x'], y = mapa['y'], z = mapa['z'];
|
||||
return x.every(finite) && y.every(finite) && z.length === y.length
|
||||
&& z.every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
|
||||
&& Array.isArray(mapa['electrodos']) && mapa['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y']));
|
||||
}
|
||||
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']))
|
||||
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);
|
||||
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)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user