Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 29d021b347 | |||
| 98e9b60e83 | |||
| 5061350dd8 | |||
| eb887be447 | |||
| 0b22b3c309 | |||
| 6ade415f63 | |||
| 5791928976 | |||
| f4d1829cd3 | |||
| 069cc459a4 | |||
| 881c613744 | |||
| be46429627 | |||
| 25f584c864 | |||
| 561a5dde36 | |||
| bf89099ce8 | |||
| ff1f6758ba | |||
| f38a2c6bb4 | |||
| 40c19a6a1f | |||
| 329c0891ae | |||
| 34c6f2af3a | |||
| 7ab2567dc9 | |||
| 14d6875d9b | |||
| f82ce8cc38 | |||
| 61867ff973 | |||
| 8bca0fbcdf | |||
| ec8542de9f | |||
| 29c9e6853b | |||
| b1ff6cadb2 | |||
| 26285a87fa | |||
| f058f1f476 | |||
| 7f1e43bdc5 | |||
| 5bf6af8ecf | |||
| 253290ed6a | |||
| ec5b8fde6b | |||
| 2a36397fac | |||
| eada50d2ff | |||
| 396902541d | |||
| 68b5e927e7 | |||
| 990cab0e37 | |||
| 39e1e3e094 | |||
| 4e08bb8c4b | |||
| 686580af81 | |||
| 60c71bfc3d | |||
| ad4edbe2a1 | |||
| 1af0c21291 | |||
| dd356efb6b | |||
| 01271621b7 | |||
| 4c181af291 |
@@ -1,4 +1,6 @@
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia';
|
||||
export type OrdenSeguimiento = 'reciente' | ProbabilidadClave;
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
@@ -9,13 +11,20 @@ export interface SeguimientoPaciente {
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
/** CaCu: her latest biopsy reported by the cut-off, with its grade. */
|
||||
ultima_biopsia?: { fecha: string; grado: string | null } | null;
|
||||
/** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */
|
||||
probabilidades?: Partial<Record<ProbabilidadClave, ProbabilidadHorizonte[]>> | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
}
|
||||
export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; }
|
||||
export interface SeguimientoResponse {
|
||||
simulado: boolean;
|
||||
corte: string;
|
||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
filtros: { estatus: string | null };
|
||||
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number };
|
||||
/** The horizons the models give, in years, for ordering and showing the probabilities. */
|
||||
horizontes_disponibles?: number[];
|
||||
estatus_disponibles: SeguimientoStatus[];
|
||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||
@@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string {
|
||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||
}
|
||||
/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */
|
||||
export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined {
|
||||
return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte);
|
||||
}
|
||||
/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival).
|
||||
* Every patient or an unknown status shows none: each scenario has its own models. */
|
||||
export const COLUMNAS_DE_PROBABILIDAD: Readonly<Record<string, readonly ProbabilidadClave[]>> = {
|
||||
CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'],
|
||||
};
|
||||
export const ETIQUETA_PROBABILIDAD: Readonly<Record<ProbabilidadClave, string>> = {
|
||||
lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia',
|
||||
};
|
||||
|
||||
@@ -7,6 +7,14 @@ import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia'];
|
||||
const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
||||
const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates.
|
||||
const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string');
|
||||
const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) =>
|
||||
['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad'])
|
||||
&& (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto']))));
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
|
||||
}
|
||||
@@ -17,6 +25,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string))
|
||||
|| (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios)))
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
@@ -25,7 +35,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']))
|
||||
&& biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']);
|
||||
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@@ -37,6 +48,8 @@ export class CacuSeguimientoService {
|
||||
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('estatus', query.estatus);
|
||||
if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden);
|
||||
if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte);
|
||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
@@ -97,4 +97,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
// Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the
|
||||
// horizon stop reaching the API (the list is paginated, so ordering happens there).
|
||||
it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' },
|
||||
probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }],
|
||||
cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] },
|
||||
} : item);
|
||||
const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const fila = root.querySelector('tbody tr')!;
|
||||
expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %');
|
||||
expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)');
|
||||
expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']);
|
||||
|
||||
fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1;
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1');
|
||||
req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges();
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)');
|
||||
});
|
||||
|
||||
// Fails if the columns stop following the status filtered: each scenario has its own models.
|
||||
it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' },
|
||||
probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item);
|
||||
const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim());
|
||||
expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)');
|
||||
expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false);
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)');
|
||||
expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']);
|
||||
|
||||
fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia';
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.has('orden')).toBe(false);
|
||||
req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges();
|
||||
expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false);
|
||||
expect(root.querySelector('select[name="orden"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 7,
|
||||
"total": 9,
|
||||
"link": [
|
||||
{
|
||||
"relation": "self",
|
||||
@@ -297,6 +297,123 @@
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/figuras",
|
||||
"valueString": "fig_c3r_caja"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"version": "0.1.0",
|
||||
"name": "cacu_dias_diagnostico_tratamiento",
|
||||
"title": "Tiempo de diagnóstico a tratamiento",
|
||||
"status": "active",
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.",
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-DIAGNOSTICO",
|
||||
"resource": {
|
||||
@@ -414,6 +531,123 @@
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/figuras",
|
||||
"valueString": "fig_c3r_caja"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"version": "0.1.0",
|
||||
"name": "cacu_dias_toma_tratamiento",
|
||||
"title": "Tiempo de tamizaje a tratamiento",
|
||||
"status": "active",
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del realizado.",
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-EU-TIEMPO-REPORTE",
|
||||
"resource": {
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "collection",
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "ados2-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2",
|
||||
"display": "ADOS-2"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo",
|
||||
"display": "Módulo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo.MODULO_2"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.css",
|
||||
"display": "Puntaje de severidad (CSS)"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 8
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion",
|
||||
"display": "Clasificación"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion.AUTISMO"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "SA",
|
||||
"display": "Afecto social"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 10
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "RRB",
|
||||
"display": "Comportamiento restringido y repetitivo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_a4",
|
||||
"display": "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d2",
|
||||
"display": "Manierismos de manos y dedos y otros manierismos complejos"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d4",
|
||||
"display": "Intereses inusualmente repetitivos o comportamientos estereotipados"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a6",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a7",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b1",
|
||||
"display": "Contacto visual inusual"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b12",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b2",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b3",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b5",
|
||||
"display": "Disfrute compartido durante la interacción"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b6",
|
||||
"display": "Iniciación espontánea de la atención conjunta"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b8",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Procedure",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "completed",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"performedDateTime": "1985-01-01",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "DiagnosticReport",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"result": [
|
||||
{
|
||||
"reference": "Observation/calidad-bad-scalp-triage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-clean-windows-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-internal-coverage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-line-noise-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-triage-level-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-usable-scalp-vista-previa"
|
||||
}
|
||||
],
|
||||
"conclusionCode": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/calidad",
|
||||
"code": "MALO"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "not-valid"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/duracion-min",
|
||||
"valueDecimal": 2.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/edad-meses",
|
||||
"valueDecimal": 30.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/canales",
|
||||
"valueInteger": 24
|
||||
}
|
||||
],
|
||||
"conclusion": "EEG de mala calidad: no es válido para el estudio (nivel de triaje: no_analizable).",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-bad-scalp-triage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "bad-scalp-triage",
|
||||
"display": "bad-scalp-triage"
|
||||
}
|
||||
],
|
||||
"text": "bad-scalp-triage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 0.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 2.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-clean-windows-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "clean-windows",
|
||||
"display": "clean-windows"
|
||||
}
|
||||
],
|
||||
"text": "clean-windows"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 100.0,
|
||||
"unit": "%"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 60.0,
|
||||
"unit": "%"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-internal-coverage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "internal-coverage",
|
||||
"display": "internal-coverage"
|
||||
}
|
||||
],
|
||||
"text": "internal-coverage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 1.0,
|
||||
"unit": "fraction"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 0.9,
|
||||
"unit": "fraction"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-line-noise-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "line-noise",
|
||||
"display": "line-noise"
|
||||
}
|
||||
],
|
||||
"text": "line-noise"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 9.231034526452635,
|
||||
"unit": "dB"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 45.0,
|
||||
"unit": "dB"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": false
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-triage-level-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "triage-level",
|
||||
"display": "triage-level"
|
||||
}
|
||||
],
|
||||
"text": "triage-level"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueString": "no_analizable",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-usable-scalp-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "usable-scalp",
|
||||
"display": "usable-scalp"
|
||||
}
|
||||
],
|
||||
"text": "usable-scalp"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 19.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 12.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click.
|
||||
// Fixture: a host component that projects one line of text into the button.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
|
||||
@Component({ imports: [IndicadorAyuda], template: `<app-indicador-ayuda etiqueta="Cómo leer: prueba" (opened)="aperturas = aperturas + 1">Texto de ayuda</app-indicador-ayuda>` })
|
||||
class Host { aperturas = 0; }
|
||||
|
||||
describe('Ayuda redonda', () => {
|
||||
function crear() {
|
||||
const fixture = TestBed.createComponent(Host);
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const boton = () => root.querySelector<HTMLButtonElement>('.ayuda-boton')!;
|
||||
const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim();
|
||||
const ayuda = root.querySelector('.ayuda')!;
|
||||
return { fixture, boton, texto, ayuda };
|
||||
}
|
||||
|
||||
it('muestra el texto al pasar el cursor y lo oculta al salir', () => {
|
||||
// Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned.
|
||||
const { fixture, texto, ayuda } = crear();
|
||||
expect(texto()).toBeUndefined();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('un clic fija el texto hasta el siguiente clic', () => {
|
||||
// Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it.
|
||||
const { fixture, boton, texto, ayuda } = crear();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('true');
|
||||
boton().click(); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
|
||||
it('avisa solo al abrirse con un clic y nombra el botón', () => {
|
||||
// Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost.
|
||||
const { fixture, boton } = crear();
|
||||
boton().click(); boton().click(); boton().click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.aperturas).toBe(2);
|
||||
expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
|
||||
// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click.
|
||||
@Component({
|
||||
selector: 'app-indicador-ayuda',
|
||||
template: `
|
||||
<div class="ayuda" (mouseenter)="sobre.set(true)" (mouseleave)="sobre.set(false)" (focusin)="sobre.set(true)" (focusout)="sobre.set(false)">
|
||||
<button type="button" class="ayuda-boton" [attr.aria-label]="etiqueta()" [attr.aria-expanded]="visible()"
|
||||
[attr.aria-controls]="visible() ? idPanel : null" (click)="alternar()"><span aria-hidden="true">?</span></button>
|
||||
@if (visible()) {
|
||||
<div class="ayuda-texto" role="tooltip" [id]="idPanel"><ng-content /></div>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
styles: `
|
||||
:host { position: absolute; top: .5rem; right: .5rem; z-index: 2; }
|
||||
.ayuda { position: relative; }
|
||||
.ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0;
|
||||
border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||
.ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent);
|
||||
border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorAyuda {
|
||||
readonly etiqueta = input('Cómo leer');
|
||||
readonly opened = output<void>();
|
||||
readonly sobre = signal(false);
|
||||
readonly fijo = signal(false);
|
||||
private static contador = 0;
|
||||
readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador;
|
||||
visible() { return this.sobre() || this.fijo(); }
|
||||
alternar() {
|
||||
const abre = !this.fijo();
|
||||
this.fijo.set(abre);
|
||||
if (abre) this.opened.emit();
|
||||
}
|
||||
}
|
||||
@@ -24,16 +24,18 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
|
||||
const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados'];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
@if (!conteos) {
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
@@ -81,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.graphic-region { flex: 1; min-width: 0; }
|
||||
:host(.dual-card) { grid-column: 1 / -1; }
|
||||
:host(.doble) { grid-column: span 2; }
|
||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||
@@ -108,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
h2.con-ayuda { padding-right: 2.5rem; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
@@ -137,6 +141,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
}
|
||||
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||
get sobrio() { return true; }
|
||||
// TEA's stacked case charts span two columns of its three-column grid.
|
||||
get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<mat-card class="figure-card" [class.sin-marco]="ayudaRedonda" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected && ayudaRedonda) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + selected.titulo" (opened)="!metadata && metadataRequested.emit()">
|
||||
<ul class="ayuda-lista">@for (line of interpretation; track $index) { <li>{{ line }}</li> }</ul>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
@for (note of state.footnotes; track $index) { <p class="ayuda-nota">{{ note }}</p> }
|
||||
}
|
||||
</app-indicador-ayuda>
|
||||
} @else if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||
@@ -37,8 +44,10 @@
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
@if (!ayudaRedonda) {
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
}
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
@@ -84,7 +93,7 @@
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<div class="highlight-legend" [class.sin-estado]="ayudaRedonda" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; }
|
||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||
.interpretation { grid-row: 1; }
|
||||
.figure-legend { grid-row: 3; min-width: 0; }
|
||||
@@ -117,6 +118,7 @@
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
@@ -126,3 +128,6 @@
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
.ayuda-lista { margin: 0; padding-left: 1.1rem; }
|
||||
.ayuda-nota { margin: .5rem 0 0; }
|
||||
|
||||
@@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||
});
|
||||
|
||||
it('con la ayuda redonda no repite el título ni el nombre de la figura', () => {
|
||||
// Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title.
|
||||
fixture.componentRef.setInput('ayudaRedonda', true);
|
||||
ready({ data: [{ y: [1] }], layout: {} });
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('.figure-title')).toBeNull();
|
||||
expect(root.querySelector('.figure-id')).toBeNull();
|
||||
expect(root.querySelector('.ayuda-boton')).not.toBeNull();
|
||||
expect(root.querySelector('.interpretation')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
@@ -41,7 +42,7 @@ export interface FigureState {
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
@@ -142,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
// A round "?" button with the reading guide instead of the «Cómo leer» box.
|
||||
@Input() ayudaRedonda = false;
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
|
||||
@@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
// These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec.
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
@@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
|
||||
@@ -23,9 +23,10 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
host: { '[class.ayuda-externa]': 'conAyudaRedonda' },
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [class.sin-linea]="conAyudaRedonda" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@if (sidebar) {
|
||||
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||
@@ -110,7 +111,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
<app-indicador-figure-card [ayudaRedonda]="conAyudaRedonda" [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@@ -130,6 +131,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
:host { display: grid; min-width: 0; }
|
||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||
.sin-linea .panel-controls { border-top: 0; padding-block: 0; }
|
||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||
@@ -166,6 +168,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||
:host { container-type: inline-size; }
|
||||
// A container is a containing block for absolute children; the round help must reach the outer card.
|
||||
:host(.ayuda-externa) { container-type: normal; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
@@ -198,6 +202,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
// Round "?" help instead of the «Cómo leer» box; TEA draws it unless told otherwise.
|
||||
@Input() ayudaRedonda?: boolean;
|
||||
get conAyudaRedonda() { return this.ayudaRedonda ?? this.dominio === 'tea'; }
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
|
||||
@@ -8,12 +8,7 @@
|
||||
}
|
||||
@if (model(); as m) {
|
||||
<div class="controls">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo</mat-label>
|
||||
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
|
||||
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@if (m.period) { <p class="period">Periodo: {{ periodLabel(m.period) }}</p> }
|
||||
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||
@@ -22,15 +17,17 @@
|
||||
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||
@else if (figure(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento.
|
||||
El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos.
|
||||
Las medianas de los tramos no tienen que sumar el tiempo acumulado.
|
||||
}
|
||||
</p>
|
||||
<details class="how-to-read"><summary>Cómo leer</summary>
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él.
|
||||
El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos,
|
||||
y las medianas de los tramos no suman el acumulado.
|
||||
}
|
||||
</p>
|
||||
</details>
|
||||
}
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||
.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); }
|
||||
.note { color: var(--issste-text-secondary); max-width: 70ch; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
|
||||
@@ -64,8 +64,10 @@ describe('Ruta del tamizaje: componente', () => {
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
|
||||
// the period follows the page's filter, with no request of its own
|
||||
f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges();
|
||||
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||
expect(f.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||
http.expectNone(() => true);
|
||||
@@ -79,6 +81,17 @@ describe('Ruta del tamizaje: componente', () => {
|
||||
expect(text).toContain('mediana 35.7');
|
||||
expect(text).toContain('Suprimido');
|
||||
});
|
||||
it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => {
|
||||
// Fails if the reading note goes back to an open paragraph under the chart.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id));
|
||||
const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement;
|
||||
expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer');
|
||||
expect(guia.open).toBe(false);
|
||||
expect(guia.textContent).toContain('bigote: Q1 a Q3');
|
||||
expect(f.nativeElement.querySelector('section > p.note')).toBeNull();
|
||||
});
|
||||
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
// Fails if an empty route draws a chart or hides the reason.
|
||||
f.detectChanges();
|
||||
|
||||
@@ -3,9 +3,7 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||
@@ -16,7 +14,7 @@ import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, ro
|
||||
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||
@Component({
|
||||
selector: 'app-indicador-screening-route',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-screening-route.html',
|
||||
styleUrl: './indicador-screening-route.scss',
|
||||
})
|
||||
@@ -24,17 +22,18 @@ export class IndicadorScreeningRoute {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly tipo = input<TipoPeriodo>('semestre');
|
||||
/** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */
|
||||
readonly periodos = input<readonly string[] | undefined>(undefined);
|
||||
/** The measures load once the region is visible. */
|
||||
readonly visible = input(true);
|
||||
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly message = signal('');
|
||||
readonly view = signal<RouteView>('cumulative');
|
||||
readonly requestedPeriod = signal<string | undefined>(undefined);
|
||||
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||
readonly model = computed(() => {
|
||||
const data = this.payloads();
|
||||
return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined;
|
||||
return data ? routeModel(data, this.tipo(), this.periodos()) : undefined;
|
||||
});
|
||||
readonly figure = computed(() => {
|
||||
const model = this.model();
|
||||
@@ -56,7 +55,6 @@ export class IndicadorScreeningRoute {
|
||||
}
|
||||
|
||||
retry() { this.load(this.dominio(), this.tipo()); }
|
||||
selectPeriod(period: string) { this.requestedPeriod.set(period); }
|
||||
selectView(view: RouteView) { this.view.set(view); }
|
||||
|
||||
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||
@@ -67,7 +65,7 @@ export class IndicadorScreeningRoute {
|
||||
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: data => {
|
||||
try {
|
||||
const model = routeModel(data, tipo, this.requestedPeriod());
|
||||
const model = routeModel(data, tipo, this.periodos());
|
||||
this.payloads.set(data);
|
||||
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
|
||||
@@ -59,8 +59,8 @@ describe('Dona de dos anillos para C1', () => {
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, tomado de la paleta compartida', () => {
|
||||
const colores = ['#A8C243', '#42C29C', '#9C42C2'];
|
||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||
|
||||
@@ -13,8 +13,8 @@ export const C2_PALETTE = Object.freeze({
|
||||
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||
]),
|
||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||
// Age groups of the EEG indicators (M21, M22): the same lime, teal and purple the other domains' series use.
|
||||
edades: Object.freeze(['#A8C243', '#42C29C', '#9C42C2']),
|
||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
||||
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied })) fixture.componentRef.setInput(name,value);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied, ayudaRedonda: false })) fixture.componentRef.setInput(name,value);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
|
||||
@@ -107,13 +107,14 @@ const reporteDe = (m: Measure, conteos: number[]): Report => ({
|
||||
|
||||
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
|
||||
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
|
||||
// Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none
|
||||
// Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none
|
||||
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
|
||||
// checked against the renderer.
|
||||
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
|
||||
expect(figuras).toEqual({
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_riesgo_banda: [], ind1: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// Covers how the Indicadores tab arranges CaCu's figures: the five times of «Tiempo de tamizaje a diagnóstico» under
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures with the
|
||||
// pending «Progresión por grupo de riesgo». Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures. Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
@@ -40,31 +39,24 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||
|
||||
it('las cinco figuras conservan su orden y las ausentes quedan como pendientes', () => {
|
||||
it('las figuras disponibles conservan su orden sin reservas vacías', () => {
|
||||
// Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose
|
||||
// the names of the request.
|
||||
abrir(CACU);
|
||||
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
});
|
||||
|
||||
it('con la ruta del tamizaje la gráfica dibuja colposcopía y biopsia y no hay una segunda tarjeta ni una pendiente', () => {
|
||||
// Fails if the measures only the route chart draws get a card (or a «pendiente» slot) next to it, which the route
|
||||
// chart's own page spec forbids.
|
||||
it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => {
|
||||
// Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it.
|
||||
abrir([...CACU, ...RUTA]);
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
expect(root().querySelector('.subsection-title')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([]);
|
||||
expect(root().querySelector('app-indicador-screening-route')).not.toBeNull();
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica',
|
||||
'figura-pendiente: Progresión por grupo de riesgo']);
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
});
|
||||
|
||||
it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => {
|
||||
@@ -73,7 +65,6 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(root().querySelector('app-indicador-screening-route')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
@@ -87,14 +78,13 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(titulosKpi).not.toContain('Días de toma a resultado');
|
||||
});
|
||||
|
||||
it('los indicadores clínicos son los dos pedidos más «Progresión por grupo de riesgo» pendiente, sin tarjetas vacías', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card or if the pending
|
||||
// figure is not drawn as such.
|
||||
it('los indicadores clínicos son los dos pedidos, sin tarjetas vacías ni figuras pendientes', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card, or if a pending
|
||||
// figure («Progresión por grupo de riesgo», withdrawn) comes back.
|
||||
abrir(CACU);
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica',
|
||||
'figura-pendiente: Progresión por grupo de riesgo']);
|
||||
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')?.textContent).toContain('Integración pendiente');
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull();
|
||||
});
|
||||
|
||||
it('Datos y definiciones conserva todo el catálogo', () => {
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||
open('cama', CAMA);
|
||||
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6');
|
||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||
});
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
|
||||
@@ -217,7 +217,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||
]);
|
||||
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6, por paciente y por mastografía');
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.label)).toEqual(h3);
|
||||
|
||||
@@ -17,9 +17,11 @@ import {
|
||||
import * as fx from './indicadores-fhir.fixtures';
|
||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import vistaPreviaBundle from './fixtures/tea_vista_previa_bundle.json';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
@@ -35,12 +37,12 @@ const curva = {
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
|
||||
outcome: { coding: [{ system: `${CS}/tea-ados2-resultado`, code: 'ados2_item_11', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=1' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
@@ -146,6 +148,24 @@ describe('Indicadores sobre FHIR', () => {
|
||||
const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {});
|
||||
for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta);
|
||||
expect(dibujo).not.toContain('Malo');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar']);
|
||||
});
|
||||
|
||||
it('presenta Aceptable en ambas gráficas cuando M29 lo declara como categoría propia', () => {
|
||||
const actual = measure('M29-calidad-eeg');
|
||||
const conAceptable: Measure = {
|
||||
...actual, extension: [...actual.extension ?? [], { url: `${SD}/categoria`, extension: [
|
||||
{ url: 'codigo', valueCode: 'ACEPTABLE' }, { url: 'etiqueta', valueString: 'ACEPTABLE' },
|
||||
] }],
|
||||
};
|
||||
const datos = datosDeReportes(conAceptable, [reports(fx.m29Semestres)[0]], 'semestre');
|
||||
expect(datos.filas.find(fila => fila['categoria'] === 'ACEPTABLE')).toMatchObject({ n: 0 });
|
||||
const figura = c2Figure(datos, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figura.status).toBe('supported');
|
||||
expect(JSON.stringify(figura.status === 'supported' ? figura.figure : {})).toContain('Aceptable');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar', 'Aceptable']);
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
@@ -329,7 +349,7 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
resultado: 'ados2_item_11', resultado_etiqueta: 'Mostrar', evento: '>=1', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
@@ -356,4 +376,27 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||
});
|
||||
|
||||
it('las regiones del mapa son las zonas del análisis del EEG', () => {
|
||||
// Pins down: Fz is its own region (frontal media) and the central region averages C3, Cz and C4 only, as the
|
||||
// EEG analysis's zones do, so a region on the map is the zone the association model names. Fails if Fz goes
|
||||
// back into the central average or the frontal media region disappears.
|
||||
const mapa = mapaDeElectrodos('picos_paroxisticos', 'Picos paroxísticos', { Fz: 3, C3: 1, Cz: 1.5, C4: 2 });
|
||||
expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([
|
||||
['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]);
|
||||
});
|
||||
|
||||
it('la vista previa de un EDF y su ADOS-2 se lee como la ficha de un paciente guardado', async () => {
|
||||
// The fixture is what `POST /governance/tea/eeg/preview` answered for a short synthetic EDF with an ADOS-2 report.
|
||||
// Pins that the bundle the server builds without storing anything passes the same converter and checks as a
|
||||
// stored patient's summary. Fails if the server's shape and the converter drift apart.
|
||||
const answer = firstValueFrom(service.vistaPrevia(vistaPreviaBundle));
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush({ concept: [] });
|
||||
const detalle = await answer;
|
||||
expect(detalle.id_seudonimo).toBe('vista-previa');
|
||||
expect(detalle.ados2?.modulo).toBe('2');
|
||||
expect(detalle.ados2?.dominios.length).toBe(2);
|
||||
expect(detalle.eeg?.calidad).toBe('malo');
|
||||
expect(detalle.eeg?.criterios_calidad.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -62,7 +62,7 @@ const percent = (value: number | null) => value === null ? null : round1(value *
|
||||
// Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data.
|
||||
// TEA's EEG quality shows its invalid exams as «No aceptable».
|
||||
const ROTULOS_DE_CATEGORIA: Readonly<Record<string, Readonly<Record<string, string>>>> = {
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable' },
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable', ACEPTABLE: 'Aceptable' },
|
||||
};
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Presentation labels for representations confirmed in the published catalog.
|
||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
|
||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||
|
||||
@@ -96,20 +96,16 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
// the page gives it, and with the contract the panel expects.
|
||||
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
|
||||
const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']);
|
||||
for (const panel of activos) {
|
||||
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
|
||||
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||
}
|
||||
});
|
||||
it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => {
|
||||
const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo);
|
||||
expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([
|
||||
['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'C3r'],
|
||||
['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'],
|
||||
['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'],
|
||||
]);
|
||||
// The risk bands are in the catalog and stay reserved.
|
||||
it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => {
|
||||
// Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure.
|
||||
expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]);
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,8 +19,9 @@ const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStar
|
||||
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
|
||||
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
|
||||
const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const RESERVADOS: string[] = [];
|
||||
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||
@@ -75,7 +76,7 @@ describe('Histórico de CaCu', () => {
|
||||
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
|
||||
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
|
||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!;
|
||||
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!;
|
||||
|
||||
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
|
||||
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
|
||||
@@ -95,21 +96,21 @@ describe('Histórico de CaCu', () => {
|
||||
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||
});
|
||||
it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => {
|
||||
it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(graficas()).toHaveLength(6);
|
||||
const reservados = paneles().slice(6);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
const reservados = paneles().slice(ACTIVOS.length);
|
||||
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||
expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual(
|
||||
HISTORICO_CACU.slice(6).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
});
|
||||
it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => {
|
||||
// Pins down: the state of a reserved panel comes from the config alone.
|
||||
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||
montar(catalogo, true); responder();
|
||||
expect(paneles().slice(6).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(3).fill('Trabajo en desarrollo'));
|
||||
expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo'));
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
});
|
||||
@@ -122,7 +123,7 @@ describe('Histórico de CaCu', () => {
|
||||
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
@@ -130,7 +131,7 @@ describe('Histórico de CaCu', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
@@ -176,7 +177,7 @@ describe('Histórico de CaCu', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||
@@ -188,7 +189,7 @@ describe('Histórico de CaCu', () => {
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo');
|
||||
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
});
|
||||
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||
montar(CATALOGO, true);
|
||||
@@ -196,17 +197,17 @@ describe('Histórico de CaCu', () => {
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('private');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||
reintentar.click(); fixture.detectChanges(); responder();
|
||||
expect(graficas()).toHaveLength(6);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
});
|
||||
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
|
||||
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
|
||||
const panel = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
});
|
||||
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
|
||||
@@ -226,7 +227,7 @@ describe('Histórico de CaCu', () => {
|
||||
}
|
||||
});
|
||||
it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
||||
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
|
||||
montar(RESERVADOS.map(item), true);
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
|
||||
@@ -81,13 +81,21 @@ describe('Histórico de CaMa', () => {
|
||||
});
|
||||
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual([
|
||||
'Días de la toma de la mastografía a su resultado',
|
||||
'Días del resultado de la mastografía al diagnóstico',
|
||||
'Días de tamizaje a diagnóstico',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'Resultado histopatológico',
|
||||
'Tasa de confirmación histopatológica',
|
||||
]);
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']);
|
||||
expect(paneles()).toHaveLength(7);
|
||||
const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo);
|
||||
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
|
||||
expect(graficas().some(g => g.label?.startsWith('Trazabilidad de ' + titulo))).toBe(true);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||
});
|
||||
|
||||
@@ -42,7 +42,7 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
];
|
||||
|
||||
// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved.
|
||||
// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask.
|
||||
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
@@ -50,12 +50,9 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana',
|
||||
enDesarrollo: true, fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'] },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana',
|
||||
enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas',
|
||||
enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
|
||||
@@ -137,22 +137,27 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en
|
||||
});
|
||||
it('resultado histopatológico y mastografías BI-RADS 4, 5 ó 6 usan el pie de total por categoría', () => {
|
||||
// Fails if the two keep the old sentence, or if the patients' counts (which carry none) or another count gets it.
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría.';
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría';
|
||||
for (const id of ['cama_histopatologia_birads', 'cama_birads_456_mastografia']) expect(figura({ ...base('C2', MESES, cats), id } as IndicadorDatos).comoLeer).toBe(pie);
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe('');
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total');
|
||||
});
|
||||
it('M30 muestra la proporción publicada de alteraciones y deja pendiente la clasificación de EEG normal', () => {
|
||||
// Fails if children without an evaluable result are treated as normal through a complement.
|
||||
it('M30 dibuja EEG anormal y EEG normal como dos líneas complementarias', () => {
|
||||
// Fails if the normal line stops mirroring the abnormal one over the same denominator, or if a period without
|
||||
// evaluable children is drawn as normal (it stays a gap), or if the caption changes.
|
||||
const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }),
|
||||
fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos);
|
||||
const f = m30.figure as unknown as Fig;
|
||||
const lineas = f.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG con alteración detectada']);
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal', 'EEG normal']);
|
||||
expect(lineas[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(lineas[1]['y']).toEqual([37.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8');
|
||||
expect(JSON.stringify(lineas[1]['text'])).toContain('3 de 8');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]);
|
||||
expect(m30.comoLeer).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza (normal)')!['y']).toEqual([69.4, 13.7]);
|
||||
expect(m30.comoLeer).toBe('La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.');
|
||||
expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
export interface HistoricoFigura {
|
||||
contrato: string;
|
||||
figure: PlotlyFigure;
|
||||
comoLeer: string;
|
||||
notaMetodologica?: string;
|
||||
suprimidos: string[];
|
||||
sinDato: string[];
|
||||
}
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
|
||||
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
|
||||
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
|
||||
const FONDO_AZUL = '#9DBFE380';
|
||||
@@ -96,32 +94,44 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
|
||||
return { validas, suprimidos, sinDato };
|
||||
}
|
||||
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
|
||||
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
// CaMa's line charts (and TEA's, which follow them) share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
function colorDeLinea(id: string, tema: Tema) {
|
||||
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
|
||||
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
if (id.startsWith('cama_') || /^M\d+_/.test(id)) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
const linea = c2Theme(tema).line;
|
||||
return { linea, relleno: linea + '40' };
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
// Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions.
|
||||
const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0];
|
||||
|
||||
const PIE_PORCENTAJE: Readonly<Record<string, string>> = {
|
||||
cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.',
|
||||
[M30_RESULTADO_EEG]: 'Resultado experimental. La línea muestra EEG con alguna alteración detectada. La clasificación de EEG normal está pendiente de validación.',
|
||||
[M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
};
|
||||
const PIE_MEDIANA: Readonly<Record<string, string>> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id,
|
||||
'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.']));
|
||||
const PIE_CATEGORIAS: Readonly<Record<string, string>> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id,
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría.']));
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría']));
|
||||
|
||||
type Trazo = Omit<HistoricoFigura, 'contrato'>;
|
||||
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
const nombre = data.id === M30_RESULTADO_EEG ? 'EEG con alteración detectada' : 'Porcentaje';
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje');
|
||||
const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema);
|
||||
const resultadoEeg = data.id === M30_RESULTADO_EEG;
|
||||
const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje';
|
||||
const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10);
|
||||
// EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval.
|
||||
const normal = data.id === M30_RESULTADO_EEG ? [
|
||||
banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false,
|
||||
line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG },
|
||||
text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} %<br>%{text}<extra></extra>' },
|
||||
] : [];
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
@@ -132,8 +142,10 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
...normal,
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}),
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -219,25 +231,3 @@ export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: Hist
|
||||
if (!figura) throw new Error('Representación no soportada');
|
||||
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||
}
|
||||
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
|
||||
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
||||
const periodos = validar(data);
|
||||
const n = (periodo: string, categorias: readonly string[]) => {
|
||||
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
const puntos = periodos.map(periodo => {
|
||||
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
|
||||
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
|
||||
});
|
||||
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
|
||||
return {
|
||||
contrato: 'C1',
|
||||
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
|
||||
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
|
||||
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
|
||||
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Indicadores and Seguimiento, and its
|
||||
// Covers the history tab in the page: it sits between Indicadores and the risk analysis tab, and its
|
||||
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
|
||||
|
||||
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -42,14 +42,14 @@ describe('Pestaña Histórico', () => {
|
||||
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
it('TEA tiene Trazabilidad y Análisis de Riesgo', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Covers the series chips of TEA's Trazabilidad: which series a figure offers and how choosing one dims the rest.
|
||||
// Fixture: a figure with two lines, each preceded by its confidence band, as the EEG normal/anormal chart draws it.
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { resaltarSerie, seriesDe } from './indicadores-historico';
|
||||
|
||||
const figura = (): PlotlyFigure => ({ layout: {}, data: [
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza' },
|
||||
{ type: 'scatter', name: 'EEG anormal', line: { color: '#a00' }, marker: { color: '#a00' } },
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza (normal)' },
|
||||
{ type: 'scatter', name: 'EEG normal', line: { color: '#06a' } },
|
||||
] });
|
||||
|
||||
describe('Series de la trazabilidad de TEA', () => {
|
||||
it('ofrece una ficha por línea o barra y ninguna por banda', () => {
|
||||
// Fails if a confidence band becomes a chip of its own or a series loses its colour.
|
||||
expect(seriesDe(figura())).toEqual([{ nombre: 'EEG anormal', color: '#a00' }, { nombre: 'EEG normal', color: '#06a' }]);
|
||||
});
|
||||
|
||||
it('al elegir una serie atenúa las demás y sus bandas, y deja intacta la figura publicada', () => {
|
||||
// Fails if the chosen series is dimmed, if its band is dimmed with the other series, or if the original is mutated.
|
||||
const original = figura();
|
||||
const vista = resaltarSerie(original, 'EEG normal');
|
||||
expect(vista.data.map(t => t['opacity'])).toEqual([.15, .15, undefined, undefined]);
|
||||
expect(original.data.every(t => t['opacity'] === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { Subject } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
@@ -86,22 +86,15 @@ describe('Figuras de histórico', () => {
|
||||
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
|
||||
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
|
||||
});
|
||||
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
|
||||
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
|
||||
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
|
||||
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
|
||||
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
|
||||
expect(figure.data[0]['y']).toEqual([75, 25]);
|
||||
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
|
||||
});
|
||||
it('una escala compartida fija el máximo de las medianas', () => {
|
||||
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
|
||||
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
|
||||
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
|
||||
});
|
||||
it('M21 y M22 no usan verde en sus líneas', () => {
|
||||
it('las líneas de M21 y M22 siguen el morado de las de CaMa', () => {
|
||||
// Fails if TEA's lines go back to their own age colours or leave CaMa's purple mark.
|
||||
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#9C42C2'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#9C42C2');
|
||||
});
|
||||
it('rechaza contratos sin representación y filas ambiguas', () => {
|
||||
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
|
||||
@@ -179,23 +172,45 @@ describe('Pestaña Histórico', () => {
|
||||
expect(c.ventana()).toBe(5);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
|
||||
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
|
||||
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
|
||||
it('ordena y titula las ocho gráficas de Trazabilidad y agrupa los tres pasos de tiempo', () => {
|
||||
const items: Indicador[] = [
|
||||
{ id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1' },
|
||||
{ id: 'M29_calidad_eeg', titulo: 'Calidad del EEG', contrato: 'C2' },
|
||||
{ id: 'M28_casos_por_estado', titulo: 'Casos por estatus', contrato: 'C2' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', titulo: 'Días de ADOS-2 a diagnóstico', contrato: 'C3r' },
|
||||
{ id: 'M26_dias_mchat_ados2', titulo: 'Días de M-CHAT a ADOS-2', contrato: 'C3r' },
|
||||
{ id: 'M25_dias_mchat_diagnostico', titulo: 'Días de M-CHAT a diagnóstico positivo', contrato: 'C3r' },
|
||||
{ id: 'M24_confirmacion_diagnostico', titulo: 'Porcentaje de confirmación diagnóstica', contrato: 'C1' },
|
||||
{ id: 'M23_pacientes_evaluados', titulo: 'Pacientes evaluados por resultado diagnóstico', contrato: 'C2' },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1' },
|
||||
{ id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1' },
|
||||
].map(item => ({ ...item, figuras: [], tipos_periodo: ['mes'] }));
|
||||
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
|
||||
const pasos = ['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo'];
|
||||
const titulos = () => Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.panel h2'), el => el.textContent?.trim());
|
||||
expect(titulos().slice(0, 3)).toEqual(pasos);
|
||||
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
|
||||
for (const { id } of items) {
|
||||
const c2 = id.startsWith('M28');
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
|
||||
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
|
||||
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
|
||||
for (const { id, contrato } of items) {
|
||||
const periodo = '2024-01';
|
||||
const fila = contrato === 'C1' ? c1(periodo, 50) : contrato === 'C2' ? c2(periodo, 'A', 3, 0)
|
||||
: { periodo, suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 };
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato, tipo_periodo: 'mes', periodos: [periodo], filas: [fila] });
|
||||
}
|
||||
render();
|
||||
const paneles = fixture.componentInstance.paneles();
|
||||
expect(paneles.map(p => p.item.id)).toEqual(['tiempos', 'M28_casos_por_estado', 'en_proceso']);
|
||||
expect(titulos()).toEqual([
|
||||
'Tiempos del tamizaje', 'Progresión del proceso diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Flujo del proceso diagnóstico y estudios de EEG', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal',
|
||||
]);
|
||||
const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
|
||||
expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos);
|
||||
// The notes live in the round help, not as text under the chart.
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')).toBeNull();
|
||||
const ayuda = (fixture.nativeElement as HTMLElement).querySelector('.panel:last-child app-indicador-ayuda') as HTMLElement;
|
||||
ayuda.querySelector('button')!.click(); fixture.detectChanges();
|
||||
expect(ayuda.querySelector('.ayuda-texto')!.textContent).toContain('Resultado experimental.');
|
||||
});
|
||||
it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => {
|
||||
// Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped.
|
||||
|
||||
@@ -7,14 +7,16 @@ import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { defer, map, Subscription } from 'rxjs';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
||||
import { TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD } from './indicadores-kpi';
|
||||
|
||||
export { HISTORICO_CAMA };
|
||||
|
||||
@@ -31,8 +33,11 @@ type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' }
|
||||
| { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
class ContratoHistoricoInvalido extends Error {}
|
||||
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
const CASOS = 'M28_casos_por_estado';
|
||||
const TIEMPOS = TEA_FIGURAS_OPORTUNIDAD;
|
||||
const TITULOS_TEA: Readonly<Record<string, string>> = {
|
||||
M23_pacientes_evaluados: 'Progresión del proceso diagnóstico',
|
||||
M28_casos_por_estado: 'Flujo del proceso diagnóstico y estudios de EEG',
|
||||
};
|
||||
const PERSONALIZADO = -1;
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p)));
|
||||
@@ -43,29 +48,46 @@ function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
||||
}
|
||||
|
||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
|
||||
// Keep the individual cards available for loading, error and empty states.
|
||||
function agruparTiempos(paneles: Panel[]): Panel[] {
|
||||
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
|
||||
const listos = pasos.every(p => p?.estado === 'listo');
|
||||
return paneles.flatMap((panel): Panel[] => {
|
||||
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
|
||||
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
|
||||
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos del tamizaje', contrato: 'C3r' }, pasos: figuras,
|
||||
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
|
||||
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
|
||||
}
|
||||
if (listos && TIEMPOS.includes(panel.item.id)) return [];
|
||||
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
|
||||
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||
}
|
||||
return [panel];
|
||||
});
|
||||
}
|
||||
|
||||
interface SerieResaltable { nombre: string; color: string }
|
||||
const nombreDe = (trazo: Record<string, unknown>) => typeof trazo['name'] === 'string' ? trazo['name'] : '';
|
||||
// Bands are drawn with their line: they are not series of their own.
|
||||
const esBanda = (trazo: Record<string, unknown>) => trazo['fill'] === 'toself';
|
||||
function colorDe(trazo: Record<string, unknown>): string {
|
||||
const marca = trazo['marker'] as { color?: unknown } | undefined, linea = trazo['line'] as { color?: unknown } | undefined;
|
||||
const color = typeof marca?.color === 'string' ? marca.color : linea?.color;
|
||||
return typeof color === 'string' ? color : 'currentColor';
|
||||
}
|
||||
export function seriesDe(figura: PlotlyFigure): SerieResaltable[] {
|
||||
return figura.data.filter(trazo => !esBanda(trazo) && nombreDe(trazo)).map(trazo => ({ nombre: nombreDe(trazo), color: colorDe(trazo) }));
|
||||
}
|
||||
// Dims every series but the chosen one; a band follows the line drawn right after it.
|
||||
export function resaltarSerie(figura: PlotlyFigure, elegida: string): PlotlyFigure {
|
||||
const data = figura.data.map((trazo, i) => {
|
||||
const propio = esBanda(trazo) ? nombreDe(figura.data[i + 1] ?? {}) : nombreDe(trazo);
|
||||
return propio === elegida ? trazo : { ...trazo, opacity: .15 };
|
||||
});
|
||||
return { ...figura, data };
|
||||
}
|
||||
|
||||
// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them.
|
||||
const ORDEN_TEA = ['tiempos', 'M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg',
|
||||
CASOS, 'en_proceso', 'M29_calidad_eeg', M30_RESULTADO_EEG];
|
||||
const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG];
|
||||
function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; };
|
||||
return paneles.map((panel, i) => ({ panel, i })).sort((a, b) => lugar(a.panel) - lugar(b.panel) || a.i - b.i).map(({ panel }) => panel);
|
||||
@@ -75,7 +97,7 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
||||
@Component({
|
||||
selector: 'app-indicadores-historico',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorAyuda],
|
||||
template: `
|
||||
<div class="controles compacto">
|
||||
<h2>Filtros</h2>
|
||||
@@ -99,6 +121,9 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<div class="paneles">
|
||||
@for (panel of paneles(); track panel.item.id) {
|
||||
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
||||
@if (dominio() === 'tea' && panel.estado === 'listo' && panel.figura.comoLeer) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + panel.item.titulo"><p class="ayuda-texto">{{ panel.figura.comoLeer }}@if (panel.figura.notaMetodologica) { {{ panel.figura.notaMetodologica }} }</p></app-indicador-ayuda>
|
||||
}
|
||||
<h2>{{ panel.item.titulo }}</h2>
|
||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||
@if (panel.mensaje) {
|
||||
@@ -117,15 +142,26 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<div class="pasos">
|
||||
@for (paso of pasos; track paso.titulo) {
|
||||
<section><h3>{{ paso.titulo }}</h3>
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="etiquetaVista() + ' de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
@if (series(panel); as lista) {
|
||||
@if (dominio() === 'tea' && lista.length > 1) {
|
||||
<div class="series" role="group" aria-label="Resaltar una serie">
|
||||
@for (serie of lista; track serie.nombre) {
|
||||
<button type="button" [style.--swatch]="serie.color" [attr.aria-pressed]="resaltados()[panel.item.id] === serie.nombre" (click)="resaltar(panel.item.id, serie.nombre)">
|
||||
<span class="swatch" [style.background]="serie.color" aria-hidden="true"></span>{{ serie.nombre }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
||||
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
@if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
@@ -167,9 +203,9 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
|
||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
.panel { position: relative; box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; padding-right: 2.5rem; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.nota-pie { margin-top: var(--issste-space-3); padding-top: var(--issste-space-2); border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font-size: 0.8125rem; line-height: 1.4; }
|
||||
@@ -177,6 +213,14 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
.nota-pie summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.nota-pie p { margin-top: var(--issste-space-2); font: inherit; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
app-indicador-ayuda p { margin: 0; }
|
||||
.series { display: flex; flex-wrap: wrap; gap: .25rem .75rem; margin-top: var(--issste-space-3); }
|
||||
// The look of CaMa's category chips: rounded, outlined with the series colour, tinted when chosen.
|
||||
.series button { display: inline-flex; align-items: center; gap: .45rem; min-height: 36px; padding: .25rem .75rem; border: 1px solid color-mix(in srgb, var(--swatch) 55%, var(--issste-border));
|
||||
border-radius: .75rem; background: var(--issste-surface); color: inherit; font: inherit; font-size: .875rem; cursor: pointer; }
|
||||
.series button[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); font-weight: 600; }
|
||||
.series button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; }
|
||||
.panel.ancho { grid-column: 1 / -1; }
|
||||
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
@@ -186,12 +230,30 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
})
|
||||
export class IndicadoresHistorico {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
// The series each panel's chart draws, which a chip can highlight; one selection per panel.
|
||||
readonly resaltados = signal<Readonly<Record<string, string>>>({});
|
||||
series(panel: Panel): readonly SerieResaltable[] { return panel.estado === 'listo' ? seriesDe(panel.figura.figure) : []; }
|
||||
resaltar(id: string, nombre: string) {
|
||||
this.resaltados.update(actual => {
|
||||
const { [id]: previo, ...resto } = actual;
|
||||
return previo === nombre ? resto : { ...actual, [id]: nombre };
|
||||
});
|
||||
}
|
||||
// The figure of each panel with a selected series; the others keep their published figure untouched.
|
||||
readonly vistas = computed<Readonly<Record<string, PlotlyFigure>>>(() => {
|
||||
const elegidas = this.resaltados();
|
||||
return Object.fromEntries(this.paneles().flatMap(panel => {
|
||||
const nombre = elegidas[panel.item.id];
|
||||
return nombre && panel.estado === 'listo' ? [[panel.item.id, resaltarSerie(panel.figura.figure, nombre)]] : [];
|
||||
}));
|
||||
});
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
readonly catalogLoading = input(false);
|
||||
readonly catalogError = input('');
|
||||
readonly retryCatalog = output<void>();
|
||||
readonly etiquetaVista = computed(() => 'Trazabilidad');
|
||||
// What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog.
|
||||
private readonly config = computed(() => historicoDeDominio(this.dominio()));
|
||||
// The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active;
|
||||
@@ -260,7 +322,7 @@ export class IndicadoresHistorico {
|
||||
const visibles = this.recortar(carga.datos.periodos);
|
||||
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
|
||||
})) * 1.05;
|
||||
const panelDe = (item: Indicador): Panel & { datos?: IndicadorDatos } => {
|
||||
const panelDe = (item: Indicador): Panel => {
|
||||
if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' };
|
||||
const carga = cargas?.[item.id];
|
||||
if (!carga) return { item, estado: 'cargando' };
|
||||
@@ -284,7 +346,7 @@ export class IndicadoresHistorico {
|
||||
if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) {
|
||||
return { item, estado: mensaje ? 'error' : 'vacio', mensaje };
|
||||
}
|
||||
return { item, rango, estado: 'listo', figura, datos, mensaje };
|
||||
return { item, rango, estado: 'listo', figura, mensaje };
|
||||
} catch (error) {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
@@ -303,8 +365,10 @@ export class IndicadoresHistorico {
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
const paneles = agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
return this.dominio() === 'tea' ? ordenar(paneles, ORDEN_TEA) : paneles;
|
||||
const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||
if (this.dominio() !== 'tea') return items.map(panelDe);
|
||||
const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
return agruparTiempos(ordenar(paneles, ORDEN_TEA));
|
||||
});
|
||||
|
||||
constructor() {
|
||||
|
||||
@@ -78,8 +78,9 @@ describe('KPI de tratamiento de CaCu', () => {
|
||||
expect(cards[0].querySelector('.value')).toBeNull();
|
||||
expect(cards[1].querySelector('.value')?.firstChild?.textContent).toBe('7.75');
|
||||
expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD);
|
||||
expect(cards[1].textContent).toContain('El evento de tratamiento se infiere de notas clínicas');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')?.textContent).not.toContain('diagnóstico a tratamiento');
|
||||
// the cards carry no provisional notice: what the measure is lives in its technical sheet
|
||||
expect(cards[1].textContent).not.toContain('Indicador provisional');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')).toBeNull();
|
||||
expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally {
|
||||
|
||||
@@ -22,7 +22,6 @@ const CACU_TRATAMIENTO_C3R = {
|
||||
unit: 'días (mediana)',
|
||||
requiresObservations: true,
|
||||
c3rInfo: (n, q1, q3) => `${n} ${n === 1 ? 'observación' : 'observaciones'}. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`,
|
||||
note: 'Indicador provisional. El evento de tratamiento se infiere de notas clínicas, sin confirmación de que se realizó.',
|
||||
} satisfies Omit<KpiDefinition, 'id' | 'title'>;
|
||||
|
||||
export const CACU_TRATAMIENTO_KPIS: readonly KpiDefinition[] = [
|
||||
@@ -50,11 +49,11 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
// cards read the `titulo` that the API already sends.
|
||||
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
||||
// M28's last stage follows neuropediatrics and requires a good EEG.
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
||||
// M29's category of the EEGs the analysis found valid.
|
||||
export const M29_BUENO = 'BUENO';
|
||||
export const M29_MALO = 'MALO';
|
||||
// What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality.
|
||||
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
|
||||
@@ -67,17 +66,15 @@ export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg'];
|
||||
// CaCu's figures under «Indicadores de oportunidad» (section «Tiempo de tamizaje a diagnóstico») in display order. A slot
|
||||
// with no `id` has no published indicator yet and draws as pending; `titulo` is the name the page gives the figure.
|
||||
// CaCu's available figures in display order; titles are assigned when the catalog publishes them.
|
||||
export interface FiguraOportunidad { id?: string; titulo: string; }
|
||||
export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' },
|
||||
{ titulo: 'Tiempo de toma de muestra a resultado de VPH' },
|
||||
{ id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' },
|
||||
{ id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' },
|
||||
];
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. Same rules as CaCu's: an entry
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry
|
||||
// with no `id` has no published indicator yet and draws as pending.
|
||||
export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cama_eu38a', titulo: 'Tiempo de toma de mastografía a interpretación radiológica' },
|
||||
@@ -86,9 +83,8 @@ export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ titulo: 'Tiempo de diagnóstico a tratamiento' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' },
|
||||
];
|
||||
// CaCu's clinical figures in display order, and the one still to be implemented.
|
||||
// CaCu's clinical figures in display order.
|
||||
export const CACU_FIGURAS_CLINICAS: readonly string[] = ['cacu_eu7', 'cacu_confirmacion_citologia'];
|
||||
export const CACU_FIGURA_CLINICA_PENDIENTE = 'Progresión por grupo de riesgo';
|
||||
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
tea: [
|
||||
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<section class="dashboard" [class.dominio-tea]="dominio === 'tea'" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
@if (fichaPacienteAbierta()) {
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
@@ -126,14 +126,13 @@
|
||||
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
|
||||
</div>
|
||||
}
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" /> }
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" [tipo]="filters?.applied?.tipo ?? 'semestre'" [periodos]="periodosDelFiltro()" /> }
|
||||
<div class="catalog-grid">
|
||||
@for (item of clinicosItems(); track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@if (dominio === 'cacu') { <app-indicador-figura-pendiente [titulo]="figuraClinicaPendiente" /> }
|
||||
</div>
|
||||
@if (dominio === 'cama') {
|
||||
<div class="kpi-grid" style="--kpi-count: 1">
|
||||
|
||||
@@ -34,6 +34,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
// TEA draws three smaller plots per row.
|
||||
.dominio-tea .catalog-grid { --plot-height: 340px; }
|
||||
@container dashboard (min-width: 1000px) { .dominio-tea .catalog-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-flow: dense; } }
|
||||
|
||||
@media (max-width: 550px) {
|
||||
h1 { font-size: 1.5rem; }
|
||||
|
||||
@@ -227,7 +227,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||
const result = panel.result();
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
// TEA's reading guide is the round "?" button: its first opening loads the metadata once.
|
||||
const button = fixture.nativeElement.querySelector('.ayuda-boton') as HTMLButtonElement;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
@@ -287,7 +288,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
|
||||
load(); toggle(); flushAll();
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle');
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .ayuda-boton');
|
||||
input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input);
|
||||
const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf<HTMLElement>).map(e => e.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
|
||||
@@ -17,7 +17,7 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi';
|
||||
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
@@ -37,6 +37,7 @@ import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { historicoDeDominio } from './indicadores-historico-config';
|
||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
import { M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
@@ -44,9 +45,11 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
|
||||
// between its history and its follow-up list.
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_TEA: typeof SECTIONS = [
|
||||
{ id: 'resumen', label: 'Resumen' }, { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
];
|
||||
const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
export const CAMA_ANALYSIS_ENABLED = false;
|
||||
// TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them.
|
||||
@@ -56,7 +59,7 @@ function ordenTea(catalog: Indicador[]): Indicador[] {
|
||||
return [...first, ...catalog.filter(item => !named.includes(item.id))];
|
||||
}
|
||||
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
|
||||
SECTIONS_WITH_HISTORY[0], { id: 'historico', label: 'Trazabilidad' },
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
|
||||
|
||||
@@ -67,7 +70,11 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
|
||||
get sections(): typeof SECTIONS {
|
||||
if (this.dominio === 'tea') return SECTIONS_TEA;
|
||||
if (this.dominio === 'cacu') return SECTIONS_CACU;
|
||||
return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS;
|
||||
}
|
||||
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
|
||||
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
@@ -344,6 +351,12 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
/** The periods the page's filter applies, for the charts that follow it with no filter of their own (the screening
|
||||
* route); `undefined` when it applies every period. */
|
||||
periodosDelFiltro(): readonly string[] | undefined {
|
||||
const seleccion = this.filters?.applied.selection;
|
||||
return seleccion?.mode === 'explicit' ? seleccion.periodos : undefined;
|
||||
}
|
||||
// CaCu's screening route chart, once the catalog publishes every measure it reads.
|
||||
get screeningRouteAvailable() {
|
||||
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
|
||||
@@ -386,7 +399,7 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
|
||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => !item.vistas || item.vistas.includes('resumen')))
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => item.id !== M30_RESULTADO_EEG && (!item.vistas || item.vistas.includes('resumen'))))
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||
@@ -400,8 +413,9 @@ export class IndicadoresPage {
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
|
||||
});
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary, and CaCu's five times, each a
|
||||
// pending slot while the catalog does not publish its indicator. The rest are the clinical ones.
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary and CaMa's times, each a pending
|
||||
// slot while the catalog does not publish its indicator; CaCu's, only when its screening route chart isn't shown. The
|
||||
// rest are the clinical ones.
|
||||
// The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for.
|
||||
readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => {
|
||||
const items = this.searchResults().items;
|
||||
@@ -416,13 +430,12 @@ export class IndicadoresPage {
|
||||
return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo };
|
||||
});
|
||||
}
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length) return [];
|
||||
// The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while
|
||||
// it is shown, so those slots are left to the chart instead of drawn twice or as pending.
|
||||
const delaRuta = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.filter(figura => !figura.id || !delaRuta.includes(figura.id)).map(figura => {
|
||||
const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined;
|
||||
return item ? { item, titulo: item.titulo } : { titulo: figura.titulo };
|
||||
// With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to
|
||||
// each event. Without it, each time the catalog publishes with a figure keeps its own.
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => {
|
||||
const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0);
|
||||
return item ? [{ item, titulo: item.titulo }] : [];
|
||||
});
|
||||
});
|
||||
readonly clinicosItems = computed(() => {
|
||||
@@ -435,7 +448,6 @@ export class IndicadoresPage {
|
||||
}
|
||||
return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items;
|
||||
});
|
||||
readonly figuraClinicaPendiente = CACU_FIGURA_CLINICA_PENDIENTE;
|
||||
// CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it.
|
||||
readonly confirmacionCama = CAMA_CONFIRMACION_KPI;
|
||||
get confirmacionCamaPendiente() { return !this.catalog().some(item => item.id === CAMA_CONFIRMACION_KPI.id); }
|
||||
|
||||
@@ -163,7 +163,8 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -33,14 +33,14 @@ describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
|
||||
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
|
||||
|
||||
it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis'
|
||||
// keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card.
|
||||
it('con las siete medidas publicadas aparece la gráfica y ninguna de sus medidas tiene tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of every time it draws, the cytology's and the diagnosis' included (the
|
||||
// «Tiempo de tamizaje a diagnóstico» figures). Fails if the chart stops appearing, or a time it draws also shows as
|
||||
// a card.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).not.toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu_tiempo_reporte');
|
||||
for (const id of ROUTE_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu7');
|
||||
});
|
||||
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
|
||||
|
||||
@@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain.
|
||||
const esperadas = ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
const esperadas = domain === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
@@ -58,6 +58,10 @@ describe('Secciones compartidas por dominio', () => {
|
||||
harness.detectChanges();
|
||||
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
||||
expect(tracking.hidden).toBe(false);
|
||||
if (domain === 'tea') {
|
||||
expect(tracking.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA');
|
||||
expect(tracking.querySelector('select[name="estatus"]')?.closest('label')?.firstChild?.textContent?.trim()).toBe('Estatus de EEG');
|
||||
}
|
||||
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
|
||||
if (domain === 'cama') {
|
||||
// An unavailable cohort has no table and offers a retry.
|
||||
|
||||
@@ -36,7 +36,8 @@ describe('Seguimiento de CaMa: ficha del paciente', () => {
|
||||
// Fails if the export buttons leave the title row or come back under the table.
|
||||
it('has the export buttons in the row of the section title, and nothing after the pagination', () => {
|
||||
const row = root().querySelector('.title-row')!;
|
||||
expect(row.querySelector('h2')!.textContent).toContain('Seguimiento de');
|
||||
// Fails if the section heading goes back to «Seguimiento de …» instead of the name of the section tab.
|
||||
expect(row.querySelector('h2')!.textContent).toBe('Análisis de riesgos');
|
||||
expect([...row.querySelectorAll('button')].map(b => b.textContent!.trim())).toEqual(['Exportar Excel (.xlsx)', 'Exportar PDF']);
|
||||
expect(root().querySelector('nav')!.nextElementSibling).toBeNull();
|
||||
expect(root().textContent).not.toContain('Exportar resultados');
|
||||
|
||||
@@ -48,7 +48,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
}
|
||||
<div [hidden]="!!ficha()">
|
||||
<div class="title-row">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
<h2>Análisis de riesgos</h2>
|
||||
@if (data(); as respuesta) {
|
||||
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
|
||||
}
|
||||
|
||||
@@ -48,16 +48,16 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
const titles = (selector: string) => [...root().querySelectorAll(selector + ' app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('las figuras de tiempo van en oportunidad y las clínicas en su orden, sin duplicarse', () => {
|
||||
// Fails if a figure is drawn in both sections, if either order changes, or if M30 (not named by the sections)
|
||||
// disappears instead of following the clinical ones.
|
||||
// M30 belongs to Trazabilidad even when the catalog publishes it.
|
||||
open('tea', TEA);
|
||||
expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']);
|
||||
expect(titles('.graphic-section')).toEqual([
|
||||
'Pacientes evaluados por resultado diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Casos por estatus', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal']);
|
||||
'Casos por estatus', 'Calidad del EEG']);
|
||||
expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
expect(fixture.componentInstance.catalogOrder().map(item => item.id)).not.toContain('M30_resultado_eeg');
|
||||
});
|
||||
|
||||
it('un indicador no publicado deja el resto en su orden', () => {
|
||||
@@ -73,12 +73,12 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
expect(root().querySelector('app-tea-resumen-periodo')).toBeNull();
|
||||
});
|
||||
|
||||
it('la primera pestaña se llama Indicadores en los tres dominios', () => {
|
||||
// Fails if the first tab goes back to «Resumen» in any domain, or changes its section id.
|
||||
it('la primera pestaña se llama Resumen en TEA e Indicadores en CaCu y CaMa', () => {
|
||||
// Fails if TEA's first tab loses its name, if CaCu or CaMa take it, or if the section id changes.
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) {
|
||||
open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]);
|
||||
const first = root().querySelector('[role="tab"]') as HTMLElement;
|
||||
expect(first.textContent?.trim()).toBe('Indicadores');
|
||||
expect(first.textContent?.trim()).toBe(domain === 'tea' ? 'Resumen' : 'Indicadores');
|
||||
expect(first.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,7 +3,14 @@
|
||||
[registrosTemporales]="pacienteDetalle.registrosTemporales()"
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
@if (teaFicha) {
|
||||
<section class="ficha-tea" aria-label="Resumen del paciente">
|
||||
<button type="button" (click)="volverDeTea()">Volver a Seguimiento</button>
|
||||
<h2>Paciente {{ teaFicha }}</h2>
|
||||
<app-tea-paciente-resumen [id]="teaFicha" modo="resumen" />
|
||||
</section>
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado' || !!teaFicha">
|
||||
@if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (dominio === 'cama') {
|
||||
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
|
||||
@@ -48,6 +55,18 @@
|
||||
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Horizonte de la probabilidad <select name="horizonte" [(ngModel)]="draft.horizonte">
|
||||
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Ordenar por <select name="orden" [(ngModel)]="draft.orden">
|
||||
@for (o of ordenes(); track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@@ -88,7 +107,8 @@
|
||||
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<td><button class="row-toggle" type="button" [attr.aria-expanded]="teaAbierto === item.id_seudonimo" [attr.aria-controls]="'tea-detalle-' + item.id_seudonimo"
|
||||
[attr.aria-label]="(teaAbierto === item.id_seudonimo ? 'Ocultar' : 'Ver') + ' resumen del paciente ' + item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<span class="chevron" aria-hidden="true"></span>{{ item.id_seudonimo }}</button></td>
|
||||
<span class="chevron" aria-hidden="true"></span></button>
|
||||
<button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirTea(item.id_seudonimo, $event)">{{ item.id_seudonimo }}</button></td>
|
||||
<td>{{ item.grupo_edad }}</td>
|
||||
<td><span class="estado-caso" [attr.data-estado]="item.estado_caso">{{ etiquetaEstado[item.estado_caso] }}</span>
|
||||
@if (item.pendientes.length) { <small>Falta: {{ item.pendientes.join(', ') }}</small> }</td>
|
||||
@@ -97,7 +117,7 @@
|
||||
<td>{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { <small>Módulo {{ item.modulo_ados2 }}</small> }</td>
|
||||
<td>@if (item.alteraciones_eeg; as eeg) { <span class="eeg" [class.eeg-anormal]="eeg === 'anormal'">{{ eeg === 'anormal' ? 'Anormal' : 'Normal' }}</span> } @else { No disponible }</td></tr>
|
||||
@if (teaAbierto === item.id_seudonimo) {
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" (completo)="abrirTea($event)" /></td></tr>
|
||||
}
|
||||
} @empty { <tr><td colspan="7">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
@@ -107,16 +127,18 @@
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Última biopsia</th>@for (c of columnasProbabilidad(); track c) {<th scope="col">{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)</th>}<th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track identidad(item).id) {
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}<small>Fecha: {{ b.fecha }}</small> } @else { No disponible }</td>
|
||||
@for (c of columnasProbabilidad(); track c) { <td class="probabilidad">{{ probabilidad(item, c) ?? 'No disponible' }}</td> }
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
</tr>
|
||||
} @empty { <tr><td colspan="8">No hay registros para los filtros aplicados.</td></tr> }
|
||||
} @empty { <tr><td [attr.colspan]="9 + columnasProbabilidad().length">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -29,7 +29,7 @@ nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top
|
||||
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link { display: inline-flex; align-items: center; min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
|
||||
@@ -42,3 +42,4 @@ tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(i
|
||||
@media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } }
|
||||
tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); }
|
||||
// TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page.
|
||||
.ficha-tea > button { margin-bottom: .5rem; }
|
||||
|
||||
@@ -5,7 +5,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
@@ -60,10 +61,35 @@ export class IndicadoresTracking implements OnChanges {
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
/** The TEA patient whose whole record shows in place of the list. */
|
||||
teaFicha?: string;
|
||||
private controlTea?: HTMLElement;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
/** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */
|
||||
horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; }
|
||||
horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; }
|
||||
readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD;
|
||||
/** The probability columns of a follow-up status (its scenario's models); none for every patient. */
|
||||
columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] {
|
||||
return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||
}
|
||||
/** The probability columns of the list shown: those of the status it was filtered by. */
|
||||
columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); }
|
||||
/** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */
|
||||
ordenes(): { codigo: string; etiqueta: string }[] {
|
||||
return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' },
|
||||
...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))];
|
||||
}
|
||||
/** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */
|
||||
probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null {
|
||||
const h = probabilidadAl(item, clave, this.horizonteMostrado());
|
||||
if (!h) return null;
|
||||
const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : '';
|
||||
return `${porcentaje(h.probabilidad)} %${ic}`;
|
||||
}
|
||||
private applied: SeguimientoQuery = { ...this.draft };
|
||||
readonly latestStudy = latestStudy;
|
||||
readonly gruposEdad = GRUPOS_EDAD_TEA;
|
||||
@@ -87,7 +113,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.statuses = data.estatus_disponibles;
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied };
|
||||
if (!this.metadataLoaded) {
|
||||
this.metadataLoaded = true;
|
||||
@@ -118,6 +144,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
// Changing domain removes the table that holds CaMa's record, so the page is told here that no record shows.
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado' || this.camaFichaAbierta()) this.fichaPacienteAbierta.emit(false);
|
||||
this.camaFichaAbierta.set(false);
|
||||
if (this.teaFicha) this.fichaPacienteAbierta.emit(false);
|
||||
this.teaFicha = undefined; this.controlTea = undefined;
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
@@ -131,7 +159,12 @@ export class IndicadoresTracking implements OnChanges {
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); }
|
||||
apply() {
|
||||
this.draft.page_size = acotarTamano(this.draft.page_size);
|
||||
// an order by a column the chosen status doesn't show goes back to the most recent study
|
||||
if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente';
|
||||
this.load({ ...this.draft, page: 1 });
|
||||
}
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
@@ -160,6 +193,18 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||
this.teaAbierto = this.teaAbierto === id ? undefined : id;
|
||||
}
|
||||
abrirTea(id: string, evento?: Event) {
|
||||
evento?.stopPropagation();
|
||||
this.controlTea = evento?.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined;
|
||||
this.teaFicha = id;
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
volverDeTea() {
|
||||
this.teaFicha = undefined;
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
const control = this.controlTea;
|
||||
afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector });
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
|
||||
+4
-9
@@ -4,16 +4,11 @@
|
||||
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
|
||||
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
|
||||
@if (r) {
|
||||
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
|
||||
@if (escenarios().length === 0) { <p role="status">La paciente no cumple las condiciones de ningún escenario clínico de recurrencia.</p> }
|
||||
@else {
|
||||
<label class="selector">Cohorte
|
||||
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
|
||||
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
|
||||
<select [value]="escenario() ? clave(escenario()!) : ''" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track clave(f)) { <option [value]="clave(f)" [selected]="f === escenario()">{{ f.escenario }} ({{ f.cohorte_nombre }})</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
|
||||
@@ -22,7 +17,7 @@
|
||||
</section>
|
||||
<section aria-labelledby="factores-recurrencia-titulo">
|
||||
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
|
||||
@if (r && r.escenarios.length) {
|
||||
@if (escenario()) {
|
||||
<label class="selector horizons">Horizonte
|
||||
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
|
||||
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
|
||||
|
||||
+16
-18
@@ -4,15 +4,14 @@ import { switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
|
||||
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
|
||||
export const HORIZONTE_PREDETERMINADO = 60;
|
||||
|
||||
/**
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
|
||||
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
|
||||
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo» for one patient: the clinical scenarios her own age, tumor size, grade and
|
||||
* receptors place her in, from either external cohort (METABRIC or SCAN-B, named with each scenario and never mixed in one figure).
|
||||
* The scenario chosen decides the curve and the label at once; the label has a horizon (12, 36 or 60 months, 60 by default).
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-recurrencia',
|
||||
@@ -23,29 +22,28 @@ export const HORIZONTE_PREDETERMINADO = 60;
|
||||
export class CamaAnalisisRecurrencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaRecurrenciaService);
|
||||
readonly cohortes = COHORTES;
|
||||
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
|
||||
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
|
||||
private readonly cohorteElegida = signal<string | null>(null);
|
||||
private readonly escenarioElegido = signal<string | null>(null);
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
|
||||
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
|
||||
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
|
||||
/** The scenarios of the cohort chosen, from the list of that cohort only. */
|
||||
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
|
||||
readonly escenario = computed(() => {
|
||||
const lista = this.escenarios();
|
||||
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
|
||||
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
|
||||
/** The figures of her scenarios, in the order the server ranked them. */
|
||||
readonly escenarios = computed(() => {
|
||||
const r = this.respuesta();
|
||||
if (!r) return [];
|
||||
return r.deLaPaciente.map(s => r.escenarios.find(f => f.cohorte === s.cohorte && f.escenario === s.escenario))
|
||||
.filter((f): f is FiguraRecurrencia => !!f);
|
||||
});
|
||||
readonly escenario = computed(() => this.escenarios().find(f => clave(f) === this.elegido()) ?? this.escenarios()[0] ?? null);
|
||||
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
|
||||
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
|
||||
readonly factores = computed(() => {
|
||||
const f = this.escenario();
|
||||
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
|
||||
});
|
||||
readonly clave = clave;
|
||||
|
||||
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
|
||||
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
|
||||
elegirEscenario(valor: string): void { this.elegido.set(valor); }
|
||||
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
|
||||
}
|
||||
|
||||
function clave(f: FiguraRecurrencia): string { return `${f.cohorte}|${f.escenario}`; }
|
||||
|
||||
+9
-6
@@ -4,13 +4,16 @@
|
||||
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
|
||||
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
|
||||
@if (m) {
|
||||
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@if (opciones().length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (opciones().length === 1) { <p class="selector">Escenario clínico de la paciente: <strong>{{ escenario() }}</strong></p> }
|
||||
@else {
|
||||
<label class="selector">Escenarios clínicos de la paciente
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of opciones(); track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
}
|
||||
@let l = lectura();
|
||||
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
|
||||
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
|
||||
|
||||
+5
-3
@@ -9,9 +9,9 @@ import { figuraSupervivencia } from './cama-supervivencia-figura';
|
||||
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores };
|
||||
|
||||
/**
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label
|
||||
* at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on
|
||||
* the scenario the patient belongs to.
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo» of the clinical scenario the patient's own data place her in; when they place
|
||||
* her in several, a menu of those. The scenario decides the curve and the label at once, computed from the data ingested so far with the
|
||||
* model in production.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-supervivencia',
|
||||
@@ -25,6 +25,8 @@ export class CamaAnalisisSupervivencia {
|
||||
/** The menu; `undefined` while it loads, `null` when there is no model in production. */
|
||||
readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
/** Her scenarios; every scenario only if the server could not place her. */
|
||||
readonly opciones = computed(() => { const m = this.menu(); return m ? (m.deLaPaciente.length ? m.deLaPaciente : m.escenarios) : []; });
|
||||
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
|
||||
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
|
||||
map((datos): Lectura => ({ tipo: 'lista', datos })),
|
||||
|
||||
+36
-16
@@ -78,7 +78,8 @@ describe('Análisis de supervivencia', () => {
|
||||
beforeEach(() => {
|
||||
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }, { nombre: 'Estadio IV', n: 30 }],
|
||||
deLaPaciente: [{ nombre: 'Estadio I', n: 80 }, { nombre: '< 45 años', n: 100 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
@@ -89,12 +90,12 @@ describe('Análisis de supervivencia', () => {
|
||||
return f;
|
||||
};
|
||||
|
||||
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
|
||||
it('opens on the patient\'s scenario with the menu the API gave', () => {
|
||||
// Fails if the menu does not open on the patient's scenario, or offers a scenario her data do not place her in.
|
||||
it('opens on the patient\'s scenario and offers only hers', () => {
|
||||
const f = montar();
|
||||
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
|
||||
|
||||
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
|
||||
expect(opciones).toEqual(['Estadio I', '< 45 años']);
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
|
||||
});
|
||||
@@ -104,7 +105,7 @@ describe('Análisis de supervivencia', () => {
|
||||
const f = montar();
|
||||
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
|
||||
|
||||
elegir(f, 'Escenario clínico', '< 45 años');
|
||||
elegir(f, 'Escenarios clínicos de la paciente', '< 45 años');
|
||||
|
||||
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
|
||||
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
|
||||
@@ -112,6 +113,25 @@ describe('Análisis de supervivencia', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de supervivencia de una paciente con un solo escenario', () => {
|
||||
// Fails if a patient whose data place her in one scenario is asked to choose: the scenario is named and drawn, with no menu.
|
||||
it('names her one scenario and draws it without a menu', () => {
|
||||
const consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: null }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }],
|
||||
deLaPaciente: [{ nombre: 'Toda la cohorte', n: 500 }], predeterminado: 'Toda la cohorte' }), consulta } }] });
|
||||
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
||||
f.componentRef.setInput('pacId', '9');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
|
||||
expect((f.nativeElement as HTMLElement).querySelector('select')).toBeNull();
|
||||
expect(texto(f)).toContain('Escenario clínico de la paciente: Toda la cohorte');
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Toda la cohorte');
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de recurrencia', () => {
|
||||
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
|
||||
it('scales the y axis to the months it draws', () => {
|
||||
@@ -130,7 +150,8 @@ describe('Análisis de recurrencia', () => {
|
||||
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
|
||||
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
|
||||
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' },
|
||||
de_la_paciente: [{ cohorte: 'scanb', escenario: 'Grado 3' }, { cohorte: 'metabric', escenario: '< 45 años' }] });
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
@@ -143,24 +164,23 @@ describe('Análisis de recurrencia', () => {
|
||||
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
|
||||
.querySelectorAll('option');
|
||||
|
||||
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
|
||||
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
|
||||
// Fails if the menu offers a cohort selector or scenarios the patient's covariates do not place her in, or does not open on the first.
|
||||
it('offers only the patient\'s scenarios, each with its cohort, and opens on the first', () => {
|
||||
const f = montar();
|
||||
|
||||
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].some(l => l.textContent!.includes('Cohorte'))).toBe(false);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['Grado 3 (SCAN-B)', '< 45 años (METABRIC)']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her first scenario, the label at 60 months
|
||||
});
|
||||
|
||||
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
|
||||
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
|
||||
// Fails if choosing another of her scenarios leaves the previous curve or label on screen: the cohorts are never mixed.
|
||||
it('changes the curve and the label together when she has another scenario chosen, and keeps one curve', () => {
|
||||
const f = montar();
|
||||
|
||||
elegir(f, 'Cohorte', 'metabric');
|
||||
elegir(f, 'Escenario clínico', 'metabric|< 45 años');
|
||||
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
|
||||
expect(texto(f)).toContain('Marca=metabric-60');
|
||||
expect(texto(f)).not.toContain('scanb');
|
||||
expect(texto(f)).not.toContain('Marca=scanb');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export interface CurvasSupervivencia {
|
||||
n: number; events: number; median_follow_up_months: number;
|
||||
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
km_adjusted: { months: number[]; S: number[] };
|
||||
km_adjusted?: { months: number[]; S: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
|
||||
@@ -50,7 +50,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
|
||||
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|
||||
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
|
||||
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
|
||||
if (adjusted !== undefined && (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length))) invalid();
|
||||
for (const curve of [weibull, fractional]) {
|
||||
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
|
||||
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
|
||||
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
|
||||
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
|
||||
km: km as CurvasSupervivencia['km'], ...(adjusted !== undefined ? { km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'] } : {}),
|
||||
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
|
||||
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
|
||||
},
|
||||
@@ -87,7 +87,7 @@ export function filaFactores(v: unknown): FilaFactores {
|
||||
}
|
||||
|
||||
/** The scenarios the menu offers, and the one the patient belongs to first. */
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; deLaPaciente: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
/** A scenario's figure with its risk factors (`null`: it has no summary row). */
|
||||
export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; }
|
||||
/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */
|
||||
@@ -97,13 +97,13 @@ export class SeleccionRechazada extends Error {}
|
||||
export class CamaCurvasService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
|
||||
/** The scenarios the menu offers, the patient's own and her default, or `null` when there is no model in production or no cohort yet. */
|
||||
escenarios(pacId: string): Observable<MenuEscenarios | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
|
||||
map(r => {
|
||||
if (!record(r) || !Array.isArray(r['escenarios'])) invalid();
|
||||
const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
const leer = (v: unknown) => (Array.isArray(v) ? v : []).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: leer(r['escenarios']), deLaPaciente: leer(r['de_la_paciente']), predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
}),
|
||||
catchError(() => of(null)),
|
||||
);
|
||||
|
||||
@@ -20,6 +20,8 @@ export interface RespuestaRecurrencia {
|
||||
resumen: FilaFactores[];
|
||||
/** The cohort and scenario the patient's own covariates place her in first, if any. */
|
||||
predeterminado: { cohorte: string; escenario: string } | null;
|
||||
/** Every scenario her covariates place her in, the larger first within each cohort; empty when none or no patient was asked. */
|
||||
deLaPaciente: { cohorte: string; escenario: string }[];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
@@ -48,9 +50,12 @@ export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
|
||||
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
|
||||
if (!Array.isArray(v['resumen'])) invalid();
|
||||
const d = v['predeterminado'];
|
||||
const suyos = Array.isArray(v['de_la_paciente']) ? (v['de_la_paciente'] as unknown[]) : [];
|
||||
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
|
||||
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null,
|
||||
deLaPaciente: suyos.filter((e): e is Record<string, string> => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')
|
||||
.map(e => ({ cohorte: e['cohorte'], escenario: e['escenario'] })) };
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
</mat-card>
|
||||
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
|
||||
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" [estatus]="estatusCodigo" /></mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface PacienteResumen {
|
||||
identidad: IdentidadPaciente;
|
||||
grupoEdad: string | null;
|
||||
estatus: string | null;
|
||||
/** The follow-up status code (`CASO`, `PRE_COLPOSCOPIA`…): it decides which probabilities the record shows. */
|
||||
estatusCodigo: string | null;
|
||||
corte: string;
|
||||
origen: 'seguimiento-demostracion';
|
||||
citologia: { fecha: string; resultado: string | null; calidad: string | null } | null;
|
||||
|
||||
@@ -45,6 +45,7 @@ export class PacienteDetalleState {
|
||||
identidad,
|
||||
grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad,
|
||||
estatus: paciente.estatus.etiqueta,
|
||||
estatusCodigo: paciente.estatus.codigo,
|
||||
corte,
|
||||
origen: 'seguimiento-demostracion',
|
||||
citologia: paciente.ultima_citologia ? {
|
||||
|
||||
@@ -34,6 +34,7 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy {
|
||||
|
||||
get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; }
|
||||
/** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */
|
||||
get estatusCodigo() { return this.estado.tipo !== 'cerrado' ? this.estado.resumen.estatusCodigo : null; }
|
||||
get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; }
|
||||
temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); }
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ describe('Riesgo individual de la paciente CaMa', () => {
|
||||
expect(text).toContain('17.8 %');
|
||||
expect(text).toContain('25.1 %');
|
||||
expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/);
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('table.risk tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
|
||||
});
|
||||
|
||||
// Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace.
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
|
||||
import { conIntervalo, covariables, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
|
||||
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
// What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons.
|
||||
describe('Riesgo individual: qué se estima y su curva', () => {
|
||||
function setup(data: unknown, estatus: string | null = null) {
|
||||
const react = vi.fn(() => Promise.resolve());
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } },
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react, purge: vi.fn(), Plots: { resize: vi.fn() },
|
||||
addFrames: vi.fn(), deleteFrames: vi.fn() }) }] });
|
||||
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
fixture.componentRef.setInput('pacId', '42');
|
||||
fixture.componentRef.setInput('estatus', estatus);
|
||||
fixture.detectChanges();
|
||||
fixture.detectChanges();
|
||||
return { fixture, root: fixture.nativeElement as HTMLElement };
|
||||
}
|
||||
|
||||
it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => {
|
||||
expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({
|
||||
quantity: 'Probabilidad', description: 'Probabilidad de CIN2+ antes de cada horizonte.',
|
||||
outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', covariates: 'VPH y citología índice' });
|
||||
expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista());
|
||||
});
|
||||
|
||||
it('rechaza un estimando mal formado', () => {
|
||||
const data = riesgoCacuConEstimando();
|
||||
data.entry[0].resource.extension[0].extension = 'texto';
|
||||
expect(() => riesgoPacienteResponse(data, '42')).toThrow();
|
||||
});
|
||||
|
||||
it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => {
|
||||
const { root } = setup(riesgoCacuConEstimando());
|
||||
expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim()))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo');
|
||||
for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
expect(root.textContent).not.toContain('método delta');
|
||||
});
|
||||
|
||||
it('dibuja la curva solo al abrir su sección', async () => {
|
||||
const { fixture, root } = setup(riesgoCacuConEstimando());
|
||||
const details = root.querySelector('details.risk-curve') as HTMLDetailsElement;
|
||||
expect(details.querySelector('summary')!.textContent).toContain('Curva de probabilidad');
|
||||
expect(root.querySelector('app-plotly-chart')).toBeNull();
|
||||
details.open = true;
|
||||
details.dispatchEvent(new Event('toggle'));
|
||||
fixture.detectChanges();
|
||||
expect(root.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('la figura une los horizontes y pone el intervalo como banda, o como barras si falta en alguno', () => {
|
||||
const riesgo = riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo;
|
||||
const banda = figuraRiesgoPaciente([riesgo]);
|
||||
expect(banda.data).toHaveLength(3);
|
||||
expect(banda.data[2]['y']).toEqual([8, 21, 34]);
|
||||
expect(banda.data[1]['y']).toEqual([5, 15, 26]);
|
||||
expect((banda.layout['yaxis'] as any).title.text).toBe('Probabilidad (%)');
|
||||
|
||||
const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) };
|
||||
const barras = figuraRiesgoPaciente([parcial]);
|
||||
expect(barras.data).toHaveLength(1);
|
||||
expect((barras.data[0]['error_y'] as any).array[0]).toBe(0);
|
||||
});
|
||||
|
||||
it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => {
|
||||
const { root } = setup(riesgoCacuDosDesenlaces());
|
||||
expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim()))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
const fila = [...root.querySelectorAll('table.risk tbody tr')][2];
|
||||
expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim()))
|
||||
.toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']);
|
||||
});
|
||||
|
||||
it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']);
|
||||
expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen una probabilidad '
|
||||
+ 'a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), '
|
||||
+ 'respectivamente.');
|
||||
expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull();
|
||||
});
|
||||
|
||||
it('dibuja una curva por desenlace, cada una con su banda', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
const figura = figuraRiesgoPaciente(riesgos);
|
||||
const lineas = figura.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['LIEAG+', 'cáncer']);
|
||||
expect((lineas[1]['y'] as number[]).map(v => Math.round(v * 10) / 10)).toEqual([0.4, 0.9, 1.5]);
|
||||
expect(figura.data.filter(t => t['fill'] === 'tonexty')).toHaveLength(2);
|
||||
expect((figura.layout['xaxis'] as any).title.text).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
|
||||
});
|
||||
|
||||
it('escribe los porcentajes con los decimales que un riesgo pequeño necesita', () => {
|
||||
expect([0.34, 0.178, 0.015, 0.004, 0.00123, 0, 0.1, 1].map(porcentaje))
|
||||
.toEqual(['34', '17.8', '1.5', '0.4', '0.123', '0', '10', '100']);
|
||||
expect(conIntervalo({ horizonte_anios: 1, probabilidad: 0.2, ic_bajo: null, ic_alto: null })).toBe('20 % (IC no disponible)');
|
||||
});
|
||||
|
||||
it('un desenlace con otra fecha índice la dice en su columna y queda fuera de la frase', () => {
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' };
|
||||
expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01');
|
||||
expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) '
|
||||
+ 'tienen una probabilidad a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).');
|
||||
});
|
||||
|
||||
it('sin modelo de un desenlace su columna dice No disponible', () => {
|
||||
const { root } = setup(riesgoCacuConEstimando());
|
||||
const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']);
|
||||
});
|
||||
|
||||
it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => {
|
||||
const data = riesgoCacuCancerSinEstimar();
|
||||
const { root } = setup(data);
|
||||
const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim());
|
||||
expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']);
|
||||
expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población');
|
||||
const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!;
|
||||
expect(riesgo.desenlace).toBe('cin2_mas');
|
||||
expect(riesgos[1]).toMatchObject({ desenlace: 'cancer', horizontes: [], sin_estimacion: 'queda fuera de su población' });
|
||||
expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers'))
|
||||
.toHaveLength(1);
|
||||
});
|
||||
|
||||
it('una supervivencia se muestra como 1 − la probabilidad de morir, con el IC invertido, y es 1 a los 0 años', () => {
|
||||
const data = riesgoCacuConEstimando();
|
||||
const r = data.entry[0].resource;
|
||||
r.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' });
|
||||
r.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; });
|
||||
const lote = riesgoPacienteResponse(data, '42')!.riesgo;
|
||||
// at the index date every patient is alive
|
||||
expect(lote.horizontes[0]).toEqual({ horizonte_anios: 0, probabilidad: 1, ic_bajo: 1, ic_alto: 1 });
|
||||
expect(lote.horizontes[1]).toMatchObject({ horizonte_anios: 1 });
|
||||
expect(lote.horizontes[1].probabilidad).toBeCloseTo(0.92);
|
||||
expect(lote.horizontes[1].ic_bajo).toBeCloseTo(0.88);
|
||||
expect(lote.horizontes[1].ic_alto).toBeCloseTo(0.95);
|
||||
expect(encabezado(lote)).toBe('Probabilidad de supervivencia');
|
||||
});
|
||||
|
||||
it('pone las covariables al pie de la tabla y el detalle en una fila por modelo, sin versión ni estado', () => {
|
||||
const { root } = setup(riesgoCacuDosDesenlaces());
|
||||
expect(root.querySelector('.covariates-note')!.textContent).toBe('Covariables: VPH y citología índice.');
|
||||
expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(2);
|
||||
expect(root.textContent).not.toMatch(/Versión del modelo|Estado del lote/);
|
||||
expect(root.querySelector('caption')!.textContent).toContain('Probabilidad en porcentaje (0 a 100 %)');
|
||||
const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!;
|
||||
riesgos[1].estimando = { ...riesgos[1].estimando, covariates: 'otras' };
|
||||
expect(covariables(riesgos)).toBe('Covariables: Probabilidad a LIEAG+: VPH y citología índice; Probabilidad a cáncer: otras.');
|
||||
});
|
||||
|
||||
/** The Bundle of a patient scored by the CIN2+, cancer and survival models (survival first). */
|
||||
function conSupervivencia() {
|
||||
const data = riesgoCacuDosDesenlaces();
|
||||
const muerte = structuredClone(data.entry[1].resource);
|
||||
muerte.id = '14-42';
|
||||
muerte.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' });
|
||||
muerte.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; });
|
||||
data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/14-42', resource: muerte });
|
||||
data.total = 3;
|
||||
return data;
|
||||
}
|
||||
const encabezados = (root: HTMLElement) => [...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim());
|
||||
|
||||
it('a un caso solo le muestra su supervivencia, sin LIEAG+ ni cáncer, también en el detalle', () => {
|
||||
// Fails if the record stops following the follow-up status, or shows a case the risk of a disease she already has.
|
||||
const { root } = setup(conSupervivencia(), 'CASO');
|
||||
expect(encabezados(root)).toEqual(['Horizonte (años)', 'Probabilidad de supervivencia (%)']);
|
||||
expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('antes de la colposcopia muestra LIEAG+ y cáncer; después, solo LIEAG+; sin estatus, todo', () => {
|
||||
// Fails if a status shows another set of columns than the follow-up table's, or no status hides a column.
|
||||
expect(encabezados(setup(conSupervivencia(), 'PRE_COLPOSCOPIA').root))
|
||||
.toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']);
|
||||
TestBed.resetTestingModule();
|
||||
expect(encabezados(setup(conSupervivencia(), 'POST_COLPOSCOPIA').root)).toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)']);
|
||||
TestBed.resetTestingModule();
|
||||
expect(encabezados(setup(conSupervivencia()).root)).toEqual(
|
||||
['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)', 'Probabilidad de supervivencia (%)']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { PlotlyFigure } from '../indicadores.models';
|
||||
import { conIntervalo, etiquetaDesenlace } from './paciente-riesgo.presentacion';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
import { LoteRiesgoCacu } from './paciente-riesgo.models';
|
||||
|
||||
/** One color per curve, in the order of the outcomes (CIN2+, cancer, any other). */
|
||||
const COLORES = ['#6a3d9a', '#b2182b', '#1f78b4'];
|
||||
const BANDAS = ['rgba(106,61,154,.18)', 'rgba(178,24,43,.16)', 'rgba(31,120,180,.16)'];
|
||||
|
||||
/**
|
||||
* The patient's risk of each outcome at the model's horizons as small curves on one axis: the points joined by a
|
||||
* line, with the interval as a band where every horizon has one and as error bars otherwise. In percent; the axis
|
||||
* names follow the first model's estimand, and the x axis says the index date the horizons count from.
|
||||
*/
|
||||
export function figuraRiesgoPaciente(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
|
||||
const data: Record<string, unknown>[] = [];
|
||||
let maximo = 0;
|
||||
riesgos.forEach((riesgo, k) => {
|
||||
const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100);
|
||||
const color = COLORES[k % COLORES.length], nombre = etiquetaDesenlace(riesgo);
|
||||
const conIc = h.map(tieneIntervalo);
|
||||
const banda = conIc.length > 1 && conIc.every(Boolean);
|
||||
if (banda) {
|
||||
data.push(
|
||||
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false,
|
||||
hoverinfo: 'skip', legendgroup: nombre },
|
||||
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty',
|
||||
fillcolor: BANDAS[k % BANDAS.length], line: { width: 0 }, name: `IC 95 % ${nombre}`, hoverinfo: 'skip',
|
||||
legendgroup: nombre },
|
||||
);
|
||||
}
|
||||
const barras = !banda && conIc.some(Boolean) ? {
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 2, width: 6,
|
||||
array: h.map((p, i) => conIc[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0),
|
||||
arrayminus: h.map((p, i) => conIc[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) },
|
||||
} : {};
|
||||
data.push({
|
||||
type: 'scatter', mode: 'lines+markers', x, y, name: nombre, legendgroup: nombre, line: { color, width: 2 },
|
||||
marker: { color, size: 9, line: { color: 'white', width: 2 } }, ...barras,
|
||||
customdata: h.map(conIntervalo),
|
||||
hovertemplate: `%{x} ${riesgo.estimando?.horizons_unit ?? 'años'}: %{customdata}<extra>${nombre}</extra>`,
|
||||
});
|
||||
maximo = Math.max(maximo, ...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100));
|
||||
});
|
||||
const primero = riesgos[0];
|
||||
const unidad = primero?.estimando?.horizons_unit ?? 'años';
|
||||
const fechas = [...new Set(riesgos.map(r => r.fecha_indice))];
|
||||
const desde = fechas.length === 1 ? `la fecha índice (${fechas[0]})`
|
||||
: `la fecha índice de cada desenlace (${riesgos.map(r => `${etiquetaDesenlace(r)}: ${r.fecha_indice}`).join('; ')})`;
|
||||
return {
|
||||
data,
|
||||
layout: {
|
||||
margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: true, legend: { orientation: 'h', y: -0.25 },
|
||||
xaxis: { title: { text: `Horizonte (${unidad} desde ${desde})` },
|
||||
tickvals: [...new Set(riesgos.flatMap(r => r.horizontes.map(p => p.horizonte_anios)))], zeroline: false },
|
||||
yaxis: { title: { text: `${primero?.estimando?.quantity ?? 'Probabilidad'} (%)` }, rangemode: 'tozero',
|
||||
range: [0, Math.max(maximo * 1.15, 1)], zeroline: false },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -7,37 +7,72 @@
|
||||
}
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en</dt><dd><time [attr.datetime]="riesgo.evaluado_en">{{ instante(riesgo.evaluado_en) }}</time></dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@if (riesgo.horizontes.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
|
||||
<table>
|
||||
<caption>Probabilidades por horizonte desde la fecha índice</caption>
|
||||
@let todos = lectura.datos.riesgos;
|
||||
@let riesgos = conRiesgo(delEstatus(todos));
|
||||
@let riesgo = riesgos[0] ?? lectura.datos.riesgo;
|
||||
@let columnas = columnasDe(todos);
|
||||
@let filas = filasDe(lotesDe(columnas));
|
||||
@if (filas.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Riesgos por horizonte, tabla desplazable" tabindex="0">
|
||||
<table class="risk">
|
||||
<caption>Probabilidad en porcentaje (0 a 100 %) por horizonte desde la fecha índice
|
||||
({{ riesgo.fecha_indice }}), con su intervalo de confianza de 95 % entre paréntesis</caption>
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }})</th>
|
||||
@for (c of columnas; track c.encabezado) { <th scope="col">{{ c.encabezado }} (%)</th> }
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (f of filas; track f.horizonte_anios) {
|
||||
<tr>
|
||||
<th scope="row">{{ f.horizonte_anios }}</th>
|
||||
@for (c of f.celdas; track $index; let i = $index) {
|
||||
<td>@if (columnas[i].vacia; as vacia) {<span class="unavailable">{{ vacia }}</span>} @else if (c) {<span class="percentage">{{ porcentaje(c.probabilidad) }} %</span>{{ ' ' }}<span class="interval">@if (tieneIntervalo(c)) {({{ porcentaje(c.ic_bajo!) }} – {{ porcentaje(c.ic_alto!) }} %)} @else {(IC no disponible)}</span>} @else {—}</td>
|
||||
}
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@for (c of columnas; track c.encabezado) {
|
||||
@if (c.lote?.sin_estimacion; as motivo) { <p class="unavailable-note">{{ c.encabezado }}: {{ motivo }}.</p> }
|
||||
}
|
||||
@if (covariables(riesgos); as texto) { <p class="covariates-note">{{ texto }}</p> }
|
||||
<details class="risk-details">
|
||||
<summary>Detalle del modelo</summary>
|
||||
<div class="risk-scroll" role="region" aria-label="Modelos de la ficha, tabla desplazable" tabindex="0">
|
||||
<table class="models">
|
||||
<thead><tr>
|
||||
<th scope="col">Horizonte (años)</th>
|
||||
<th scope="col">Probabilidad (%)</th>
|
||||
<th scope="col">Intervalo de confianza (%)</th>
|
||||
<th scope="col">Probabilidad</th><th scope="col">Modelo</th><th scope="col">Qué se estima</th>
|
||||
<th scope="col">Desenlace</th><th scope="col">Desde</th><th scope="col">Fecha índice</th>
|
||||
<th scope="col">Evaluado en</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
@for (h of riesgo.horizontes; track h.horizonte_anios) {
|
||||
@for (r of riesgos; track r.id) {
|
||||
<tr>
|
||||
<th scope="row">{{ h.horizonte_anios }}</th>
|
||||
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
|
||||
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
|
||||
<th scope="row">{{ encabezado(r) }}</th>
|
||||
<td>{{ r.modelo_nombre }}</td>
|
||||
<td>{{ r.estimando?.description ?? '—' }}</td>
|
||||
<td>{{ r.estimando?.outcome ?? r.desenlace_texto ?? r.desenlace }}</td>
|
||||
<td>{{ r.estimando?.index_date ?? '—' }}</td>
|
||||
<td>{{ r.fecha_indice }}</td>
|
||||
<td><time [attr.datetime]="r.evaluado_en">{{ instante(r.evaluado_en) }}</time></td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
</details>
|
||||
@if (filas.length > 1) {
|
||||
<details class="risk-curve" (toggle)="curvaAbierta.set($any($event.target).open)">
|
||||
<summary>Curva{{ riesgos.length > 1 ? 's' : '' }} de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo</summary>
|
||||
@if (frase(riesgos); as texto) { <p class="risk-sentence">{{ texto }}</p> }
|
||||
@if (curvaAbierta()) {
|
||||
<app-plotly-chart [style.--plot-height]="'300px'" [showNotes]="false" [figure]="figura(riesgos)"
|
||||
[label]="'Curvas de probabilidad individual ' + rotulo() + ' por horizonte'" />
|
||||
}
|
||||
</details>
|
||||
}
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
|
||||
@@ -18,3 +18,11 @@ thead th { position: sticky; top: 0; background: var(--issste-background, var(--
|
||||
tbody th, td { background: var(--issste-surface); }
|
||||
tbody tr:last-child > * { border-bottom: 0; }
|
||||
.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
|
||||
.risk-sentence { margin: .25rem 0 .75rem; line-height: 1.5; }
|
||||
.risk-details { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
|
||||
.risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; }
|
||||
.unavailable { color: var(--issste-text-secondary); }
|
||||
.unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; }
|
||||
.covariates-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; }
|
||||
table.models { min-width: 48rem; }
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { Component, computed, effect, inject, input } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { DominioRiesgo } from './paciente-riesgo.models';
|
||||
import { Component, computed, effect, inject, input, signal } from '@angular/core';
|
||||
import { LowerCasePipe } from '@angular/common';
|
||||
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../indicadores.models';
|
||||
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
|
||||
import { ColumnaRiesgo, columnasRiesgo, conRiesgo, delEstatus, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion';
|
||||
import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
@@ -12,7 +16,7 @@ export const instanteUtc = (iso: string) => {
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-riesgo-tabla',
|
||||
imports: [DecimalPipe],
|
||||
imports: [LowerCasePipe, PlotlyChart],
|
||||
providers: [PacienteRiesgoState],
|
||||
templateUrl: './paciente-riesgo-tabla.html',
|
||||
styleUrl: './paciente-riesgo-tabla.scss',
|
||||
@@ -22,11 +26,30 @@ export class PacienteRiesgoTabla {
|
||||
readonly pacId = input.required<string | null>();
|
||||
/** The domain whose model scored her: CaCu unless said otherwise. */
|
||||
readonly dominio = input<DominioRiesgo>('cacu');
|
||||
/** Her follow-up status code: the table shows only the probabilities that status follows (a case, her survival). */
|
||||
readonly estatus = input<string | null>(null);
|
||||
readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu');
|
||||
private readonly state = inject(PacienteRiesgoState);
|
||||
readonly estado = this.state.estado;
|
||||
readonly tieneIntervalo = tieneIntervalo;
|
||||
readonly instante = instanteUtc;
|
||||
/** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */
|
||||
readonly curvaAbierta = signal(false);
|
||||
readonly porcentaje = porcentaje;
|
||||
readonly encabezado = encabezado;
|
||||
readonly etiqueta = etiquetaDesenlace;
|
||||
readonly frase = fraseRiesgo;
|
||||
readonly filasDe = filasRiesgo;
|
||||
readonly conRiesgo = conRiesgo;
|
||||
readonly covariables = covariables;
|
||||
columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio(), this.estatus()); }
|
||||
delEstatus(riesgos: LoteRiesgoCacu[]): LoteRiesgoCacu[] { return delEstatus(riesgos, this.estatus()); }
|
||||
lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); }
|
||||
private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure };
|
||||
figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure {
|
||||
if (this.figuraDe?.riesgos !== riesgos) this.figuraDe = { riesgos, figura: figuraRiesgoPaciente(riesgos) };
|
||||
return this.figuraDe.figura;
|
||||
}
|
||||
constructor() {
|
||||
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
|
||||
}
|
||||
|
||||
@@ -14,6 +14,29 @@ export interface HorizonteRiesgoCacu {
|
||||
ic_alto?: number | null;
|
||||
}
|
||||
|
||||
/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */
|
||||
export interface EstimandoRiesgo {
|
||||
/** e.g. "Probabilidad"; also `method.text`. */
|
||||
quantity?: string;
|
||||
description?: string;
|
||||
outcome?: string;
|
||||
index_date?: string;
|
||||
/** The unit the horizons are counted in, e.g. "años". */
|
||||
horizons_unit?: string;
|
||||
/** The variables the model uses, in words, as the record writes them under the table. */
|
||||
covariates?: string;
|
||||
/** `supervivencia`: the model gives the probability of the outcome (dying) and the record shows its complement. */
|
||||
complement?: string;
|
||||
}
|
||||
|
||||
/** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */
|
||||
export interface ResultadosIndice {
|
||||
escamosas?: string;
|
||||
glandulares?: string;
|
||||
/** `POSITIVO`, `NEGATIVO` or `INDETERMINADO`. */
|
||||
vph?: string;
|
||||
}
|
||||
|
||||
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
|
||||
export interface LoteRiesgoCacu {
|
||||
/** The resource's id, `<lote_id>-<pac_id>`. */
|
||||
@@ -28,12 +51,21 @@ export interface LoteRiesgoCacu {
|
||||
desenlace: string;
|
||||
desenlace_texto: string | null;
|
||||
horizontes: HorizonteRiesgoCacu[];
|
||||
/** `null` for a model whose scenario doesn't say. */
|
||||
estimando: EstimandoRiesgo | null;
|
||||
/** `null` when no cytology was sampled on the index date (or the domain doesn't give it). */
|
||||
resultados_indice: ResultadosIndice | null;
|
||||
/** Why a current model of this outcome has no risk for her (extension `sin-estimacion`; then `horizontes` is
|
||||
* empty and `fecha_indice` too); `null` when it scored her. */
|
||||
sin_estimacion: string | null;
|
||||
}
|
||||
|
||||
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
|
||||
/** DEV-only: the patient's current `RiskAssessment` of each outcome, from a `searchset` Bundle tagged `simulado`.
|
||||
* `riesgos` holds them CIN2+ first, then cancer, then any other; `riesgo` is the first. */
|
||||
export interface RiesgoPacienteCacu {
|
||||
simulado: true;
|
||||
riesgo: LoteRiesgoCacu;
|
||||
riesgos: LoteRiesgoCacu[];
|
||||
}
|
||||
|
||||
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { COLUMNAS_DE_PROBABILIDAD, ProbabilidadClave } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
/** How the record names an outcome in its columns, curves and sentence. */
|
||||
export function etiquetaDesenlace(lote: LoteRiesgoCacu): string {
|
||||
if (lote.desenlace.startsWith('cin2')) return 'LIEAG+';
|
||||
if (lote.desenlace === 'cancer') return 'cáncer';
|
||||
if (lote.desenlace === 'muerte') return lote.estimando?.complement === 'supervivencia' ? 'supervivencia' : 'muerte';
|
||||
return lote.desenlace_texto ?? lote.desenlace;
|
||||
}
|
||||
|
||||
/** A column's header: "Probabilidad a LIEAG+", "Probabilidad a cáncer"; with its own index date when it isn't
|
||||
* `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */
|
||||
export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string {
|
||||
const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : '';
|
||||
const etiqueta = etiquetaDesenlace(lote);
|
||||
return `${etiqueta === 'supervivencia' ? 'Probabilidad de supervivencia' : `Probabilidad a ${etiqueta}`}${desde}`;
|
||||
}
|
||||
|
||||
/** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8",
|
||||
* 0.015 -> "1.5", 0.00123 -> "0.123", 0.34 -> "34". */
|
||||
export function porcentaje(p: number): string {
|
||||
const v = p * 100;
|
||||
const decimales = v === 0 ? 0 : v < 1 ? 3 : v < 10 ? 2 : 1;
|
||||
const texto = v.toFixed(decimales);
|
||||
return texto.includes('.') ? texto.replace(/\.?0+$/, '') : texto;
|
||||
}
|
||||
|
||||
/** The risk with its interval in parentheses, as the table and the sentence write it. */
|
||||
export function conIntervalo(h: HorizonteRiesgoCacu): string {
|
||||
const punto = `${porcentaje(h.probabilidad)} %`;
|
||||
return tieneIntervalo(h) ? `${punto} (${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %)` : `${punto} (IC no disponible)`;
|
||||
}
|
||||
|
||||
/** The outcomes a domain's record always has a column for, even with no model: CaCu's CIN2+ and cancer. */
|
||||
const COLUMNAS_FIJAS: Record<string, { desenlace: string; etiqueta: string }[]> = {
|
||||
cacu: [{ desenlace: 'cin2', etiqueta: 'LIEAG+' }, { desenlace: 'cancer', etiqueta: 'cáncer' }],
|
||||
};
|
||||
const esDe = (lote: LoteRiesgoCacu, desenlace: string) =>
|
||||
desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace;
|
||||
|
||||
/** The outcomes the record shows for each follow-up status, the same as the follow-up table's columns: a case
|
||||
* already has the disease, so only her survival; a patient before colposcopy, LIEAG+ and cancer; after it, LIEAG+. */
|
||||
const DESENLACE_DE_LA_COLUMNA: Record<ProbabilidadClave, string> = { lieag: 'cin2', cancer: 'cancer', supervivencia: 'muerte' };
|
||||
export function desenlacesDelEstatus(estatus: string | null | undefined): string[] | null {
|
||||
const columnas = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] : undefined;
|
||||
return columnas ? columnas.map(c => DESENLACE_DE_LA_COLUMNA[c]) : null;
|
||||
}
|
||||
|
||||
/** The risks of the outcomes her follow-up status shows; all of them when the status names none. */
|
||||
export function delEstatus(riesgos: LoteRiesgoCacu[], estatus: string | null | undefined): LoteRiesgoCacu[] {
|
||||
const desenlaces = desenlacesDelEstatus(estatus);
|
||||
return desenlaces ? riesgos.filter(r => desenlaces.some(d => esDe(r, d))) : riesgos;
|
||||
}
|
||||
|
||||
export interface ColumnaRiesgo {
|
||||
encabezado: string;
|
||||
/** Its model's risks; `null` when no model of the outcome is current. */
|
||||
lote: LoteRiesgoCacu | null;
|
||||
/** What the cells say when there's no risk: no model, or a model that doesn't estimate her. */
|
||||
vacia: string | null;
|
||||
}
|
||||
|
||||
/** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any
|
||||
* other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */
|
||||
export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu', estatus: string | null = null): ColumnaRiesgo[] {
|
||||
riesgos = delEstatus(riesgos, estatus);
|
||||
const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null;
|
||||
const desenlaces = desenlacesDelEstatus(estatus);
|
||||
const fijas = (COLUMNAS_FIJAS[dominio] ?? []).filter(f => !desenlaces || desenlaces.includes(f.desenlace));
|
||||
const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => {
|
||||
const lote = riesgos.find(r => esDe(r, desenlace)) ?? null;
|
||||
if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' };
|
||||
return { encabezado: encabezado(lote, fecha), lote,
|
||||
vacia: lote.horizontes.length ? null : 'No estimada para su grupo' };
|
||||
});
|
||||
for (const lote of riesgos) {
|
||||
if (fijas.some(f => esDe(lote, f.desenlace)) || !lote.horizontes.length) continue;
|
||||
columnas.push({ encabezado: encabezado(lote, fecha), lote, vacia: null });
|
||||
}
|
||||
return columnas;
|
||||
}
|
||||
|
||||
/** The risks the record can draw and describe: the ones with horizons. */
|
||||
export const conRiesgo = (riesgos: LoteRiesgoCacu[]) => riesgos.filter(r => r.horizontes.length);
|
||||
|
||||
export interface FilaRiesgo {
|
||||
horizonte_anios: number;
|
||||
/** One cell per column, in their order; `null` where that column has no risk at this horizon. */
|
||||
celdas: (HorizonteRiesgoCacu | null)[];
|
||||
}
|
||||
|
||||
/** The table's rows: every horizon any of the columns has, ascending, with each column's risk there. */
|
||||
export function filasRiesgo(lotes: (LoteRiesgoCacu | null)[]): FilaRiesgo[] {
|
||||
const horizontes = [...new Set(lotes.flatMap(r => r?.horizontes.map(h => h.horizonte_anios) ?? []))]
|
||||
.sort((a, b) => a - b);
|
||||
return horizontes.map(horizonte_anios => ({
|
||||
horizonte_anios,
|
||||
celdas: lotes.map(r => r?.horizontes.find(h => h.horizonte_anios === horizonte_anios) ?? null),
|
||||
}));
|
||||
}
|
||||
|
||||
function resultado(r: ResultadosIndice | null): string | null {
|
||||
if (!r) return null;
|
||||
const vph = r.vph === 'POSITIVO' ? 'VPH positivo' : r.vph === 'NEGATIVO' ? 'VPH negativo'
|
||||
: r.vph ? `VPH ${r.vph.toLowerCase()}` : 'sin resultado de VPH';
|
||||
const citologia = [r.escamosas, r.glandulares].filter(Boolean).join(' con ');
|
||||
return `Un resultado de ${vph} y una citología ${citologia || 'sin resultado'}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sentence over the curves: the index results and, at the longest horizon the outcomes of the first one's index
|
||||
* date share, each outcome's
|
||||
* cumulative risk of being present at the index visit or developing afterwards, "respectivamente" when there are
|
||||
* several. `null` without the index results.
|
||||
*/
|
||||
export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null {
|
||||
const scored = conRiesgo(todos);
|
||||
const riesgos = scored.filter(r => r.fecha_indice === scored[0]?.fecha_indice); // the outcomes of the same visit
|
||||
const inicio = resultado(riesgos.find(r => r.resultados_indice)?.resultados_indice ?? null);
|
||||
if (!inicio) return null;
|
||||
const comunes = filasRiesgo(riesgos).filter(f => f.celdas.every(c => c !== null));
|
||||
const ultima = comunes[comunes.length - 1];
|
||||
if (!ultima) return null;
|
||||
const fecha = riesgos[0].fecha_indice;
|
||||
const junta = (xs: string[]) => xs.length > 1 ? `${xs.slice(0, -1).join(', ')} y ${xs[xs.length - 1]}` : xs[0];
|
||||
const desenlaces = junta(riesgos.map(etiquetaDesenlace));
|
||||
const valores = junta(ultima.celdas.map(c => conIntervalo(c!)));
|
||||
const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`;
|
||||
return `${inicio} (${fecha}) tienen una probabilidad a ${anios} de estar presente o de aparecer ${desenlaces} `
|
||||
+ `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`;
|
||||
}
|
||||
|
||||
/** The covariates under the table: each model's, by its column, or once when every model uses the same ones. */
|
||||
export function covariables(riesgos: LoteRiesgoCacu[]): string | null {
|
||||
const con = riesgos.filter(r => r.estimando?.covariates);
|
||||
if (!con.length) return null;
|
||||
const textos = [...new Set(con.map(r => r.estimando!.covariates!))];
|
||||
if (textos.length === 1) return `Covariables: ${textos[0]}.`;
|
||||
return `Covariables: ${con.map(r => `${encabezado(r)}: ${r.estimando!.covariates}`).join('; ')}.`;
|
||||
}
|
||||
@@ -44,13 +44,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
// horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval
|
||||
expect(root.querySelectorAll('table.risk thead th')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('table.risk thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('table.risk tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)');
|
||||
// the record names the model, its index date and outcome, not its version nor the batch's state
|
||||
expect(root.textContent).not.toMatch(/Final \(final\)|2\.1\.0/);
|
||||
for (const value of ['modelo-cacu', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
@@ -72,7 +74,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(getComputedStyle(scroll).overflow).toBe('auto');
|
||||
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
|
||||
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
|
||||
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
|
||||
expect(getComputedStyle(root.querySelector('table.risk thead th')!).position).toBe('sticky');
|
||||
});
|
||||
|
||||
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
|
||||
@@ -84,10 +86,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
prediccion(0.00123, '2026-06-01', '2038-09-01'),
|
||||
];
|
||||
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('table.risk tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']);
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']);
|
||||
expect(root.textContent).not.toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
export const ESTIMANDO = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
|
||||
|
||||
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
|
||||
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
|
||||
@@ -37,9 +38,7 @@ export function riesgoCacuEjemplo(): any {
|
||||
|
||||
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
|
||||
export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
return {
|
||||
simulado: true,
|
||||
riesgo: {
|
||||
const riesgo: LoteRiesgoCacu = {
|
||||
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
|
||||
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
|
||||
horizontes: [
|
||||
@@ -47,6 +46,69 @@ export function riesgoCacuVista(): RiesgoPacienteCacu {
|
||||
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
|
||||
],
|
||||
},
|
||||
estimando: null,
|
||||
resultados_indice: null,
|
||||
sin_estimacion: null,
|
||||
};
|
||||
return { simulado: true, riesgo, riesgos: [riesgo] };
|
||||
}
|
||||
|
||||
/** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */
|
||||
export function riesgoCacuConEstimando(): any {
|
||||
const data = riesgoCacuEjemplo();
|
||||
const resource = data.entry[0].resource;
|
||||
resource.method.text = 'Probabilidad';
|
||||
resource.extension = [{ url: ESTIMANDO, extension: [
|
||||
{ url: 'quantity', valueString: 'Probabilidad' },
|
||||
{ url: 'covariates', valueString: 'VPH y citología índice' },
|
||||
{ url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' },
|
||||
{ url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' },
|
||||
{ url: 'horizons_unit', valueString: 'años' },
|
||||
{ url: 'interval', valueString: 'IC 95 % por método delta' },
|
||||
{ url: 'otra', valueString: 'se ignora' },
|
||||
] }];
|
||||
return data;
|
||||
}
|
||||
|
||||
export const RESULTADOS_INDICE = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
|
||||
|
||||
/** TEST ONLY. `riesgoCacuConEstimando()` plus a cancer `RiskAssessment` of the same visit, both with the index
|
||||
* cytology's results: the Bundle a patient scored by the CIN2+ and the cancer models gets. Cancer comes first, as
|
||||
* the newer batch would. */
|
||||
export function riesgoCacuDosDesenlaces(): any {
|
||||
const data = riesgoCacuConEstimando();
|
||||
const cin2 = data.entry[0].resource;
|
||||
const resultados = { url: RESULTADOS_INDICE, extension: [
|
||||
{ url: 'escamosas', valueString: 'LIEBG' }, { url: 'vph', valueString: 'POSITIVO' }] };
|
||||
cin2.extension.push(resultados);
|
||||
const cancer = structuredClone(cin2);
|
||||
cancer.id = '13-42';
|
||||
cancer.method.coding[0].code = 'modelo-cacu-cancer';
|
||||
cancer.extension[0].extension = cancer.extension[0].extension.map((e: any) =>
|
||||
e.url === 'outcome' ? { ...e, valueString: 'Cáncer: biopsia de carcinoma' } : e);
|
||||
cancer.prediction = [
|
||||
prediccion(0.004, '2026-06-01', '2027-06-01', [0.002, 0.008]),
|
||||
prediccion(0.009, '2026-06-01', '2029-06-01', [0.005, 0.016]),
|
||||
prediccion(0.015, '2026-06-01', '2031-06-01', [0.008, 0.028]),
|
||||
].map(p => ({ ...p, outcome: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/desenlace', code: 'cancer',
|
||||
display: 'Cáncer cervicouterino por biopsia' }] } }));
|
||||
data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer });
|
||||
data.total = 2;
|
||||
return data;
|
||||
}
|
||||
|
||||
export const SIN_ESTIMACION = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
|
||||
|
||||
/** TEST ONLY. `riesgoCacuConEstimando()` plus a current cancer model that didn't score her: a `RiskAssessment` with
|
||||
* no prediction, marked `sin-estimacion`. */
|
||||
export function riesgoCacuCancerSinEstimar(): any {
|
||||
const data = riesgoCacuConEstimando();
|
||||
const cancer = structuredClone(data.entry[0].resource);
|
||||
cancer.id = '13-42';
|
||||
delete cancer.prediction;
|
||||
cancer.extension = [{ url: SIN_ESTIMACION, extension: [{ url: 'desenlace', valueCode: 'cancer' },
|
||||
{ url: 'motivo', valueString: 'queda fuera de su población' }] }];
|
||||
data.entry.push({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer });
|
||||
data.total = 2;
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isoDate } from '../cacu-seguimiento.models';
|
||||
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice, RiesgoPacienteCacu } from './paciente-riesgo.models';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
@@ -9,6 +9,11 @@ const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
|
||||
const DAYS_PER_YEAR = 365.25;
|
||||
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
|
||||
const SIMULATED = 'simulado';
|
||||
const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
|
||||
const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion';
|
||||
const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice';
|
||||
const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph'];
|
||||
const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'covariates', 'complement'];
|
||||
|
||||
function utcTimestamp(v: unknown): v is string {
|
||||
return typeof v === 'string'
|
||||
@@ -39,6 +44,40 @@ function interval(prediction: Record<string, unknown>): { ic_bajo: number | null
|
||||
return { ic_bajo: low, ic_alto: high };
|
||||
}
|
||||
|
||||
/** The resource's extension `url` as its known `keys` with a text value; `null` without that extension. */
|
||||
function stringExtension<K extends string>(resource: Record<string, unknown>, url: string,
|
||||
keys: readonly K[]): Partial<Record<K, string>> | null {
|
||||
const extensions = resource['extension'];
|
||||
if (extensions === undefined) return null;
|
||||
if (!Array.isArray(extensions)) invalid();
|
||||
const found = extensions.find(e => record(e) && e['url'] === url);
|
||||
if (found === undefined) return null;
|
||||
if (!Array.isArray(found['extension'])) invalid();
|
||||
const result: Partial<Record<K, string>> = {};
|
||||
for (const item of found['extension']) {
|
||||
if (!record(item) || !text(item['url'])) invalid();
|
||||
const key = item['url'] as K;
|
||||
if (keys.includes(key) && text(item['valueString'])) result[key] = item['valueString'];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const estimand = (resource: Record<string, unknown>): EstimandoRiesgo | null =>
|
||||
stringExtension(resource, ESTIMAND, ESTIMAND_KEYS);
|
||||
|
||||
/** The `sin-estimacion` extension: the outcome of a current model that didn't score her, and why; `null` without it. */
|
||||
function notScoredOutcome(resource: Record<string, unknown>): { desenlace: string; motivo: string } | null {
|
||||
const extensions = resource['extension'];
|
||||
if (!Array.isArray(extensions)) return null;
|
||||
const found = extensions.find(e => record(e) && e['url'] === NOT_SCORED);
|
||||
if (found === undefined) return null;
|
||||
const items = Array.isArray(found['extension']) ? found['extension'].filter(record) : invalid();
|
||||
const desenlace = items.find(i => i['url'] === 'desenlace')?.['valueCode'];
|
||||
const motivo = items.find(i => i['url'] === 'motivo')?.['valueString'];
|
||||
if (!text(desenlace)) invalid();
|
||||
return { desenlace, motivo: text(motivo) ? motivo : 'el modelo no estima a esta paciente' };
|
||||
}
|
||||
|
||||
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
|
||||
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
|
||||
const period = prediction['whenPeriod'];
|
||||
@@ -62,6 +101,15 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
const method = v['method'];
|
||||
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
|
||||
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
|
||||
const notScored = notScoredOutcome(v);
|
||||
if (notScored !== null && v['prediction'] === undefined) {
|
||||
return {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: '', evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: notScored.desenlace, desenlace_texto: null, horizontes: [], estimando: estimand(v),
|
||||
resultados_indice: null, sin_estimacion: notScored.motivo,
|
||||
};
|
||||
}
|
||||
const predictions = v['prediction'];
|
||||
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
|
||||
let start: string | undefined;
|
||||
@@ -80,7 +128,8 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
|
||||
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
|
||||
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
|
||||
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
|
||||
horizontes,
|
||||
horizontes, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS),
|
||||
sin_estimacion: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -89,16 +138,44 @@ function simulated(resource: Record<string, unknown>): boolean {
|
||||
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
|
||||
}
|
||||
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only).
|
||||
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */
|
||||
/** A model whose estimand asks for its complement (survival from a probability of dying): each horizon becomes
|
||||
* 1 − p, and its interval 1 − high to 1 − low; survival at 0 years is 1. */
|
||||
function complemento(lote: LoteRiesgoCacu): void {
|
||||
if (lote.estimando?.complement !== 'supervivencia') return;
|
||||
const horizontes = lote.horizontes.map(h => ({
|
||||
...h, probabilidad: 1 - h.probabilidad,
|
||||
ic_bajo: h.ic_alto == null ? h.ic_alto ?? null : 1 - h.ic_alto,
|
||||
ic_alto: h.ic_bajo == null ? h.ic_bajo ?? null : 1 - h.ic_bajo,
|
||||
}));
|
||||
// At its index date every patient is alive: survival at 0 years is 1, whether or not the model gives it.
|
||||
if (horizontes.length && !horizontes.some(h => h.horizonte_anios === 0)) {
|
||||
horizontes.unshift({ horizonte_anios: 0, probabilidad: 1, ic_bajo: 1, ic_alto: 1 });
|
||||
}
|
||||
lote.horizontes = horizontes;
|
||||
}
|
||||
|
||||
/** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */
|
||||
export function ordenDesenlace(desenlace: string): number {
|
||||
return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2;
|
||||
}
|
||||
|
||||
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`s, one per outcome, each tagged
|
||||
* `simulado` (DEV only), and one with no prediction for a current model that didn't score her. `riesgo` is the first
|
||||
* that has a risk. `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and
|
||||
* malformed fields. */
|
||||
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
|
||||
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
|
||||
const entries = v['entry'] ?? [];
|
||||
if (!Array.isArray(entries)) invalid();
|
||||
if (entries.length === 0) return null;
|
||||
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
|
||||
const riesgos = entries.map(entry => {
|
||||
const resource = record(entry) ? entry['resource'] : undefined;
|
||||
if (!record(resource) || !simulated(resource)) invalid();
|
||||
return riskAssessment(structuredClone(resource), pacId);
|
||||
});
|
||||
riesgos.forEach(complemento);
|
||||
riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace));
|
||||
return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos };
|
||||
}
|
||||
|
||||
/** Presentation helper: an incomplete interval must never become a fabricated range. */
|
||||
|
||||
@@ -49,6 +49,17 @@ describe('Ruta del tamizaje: modelo', () => {
|
||||
expect(routeModel(data, 'semestre').period).toBe('2025-S2');
|
||||
expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1');
|
||||
});
|
||||
it('con los periodos del filtro de la página se usa el más reciente de ellos con cajas publicadas', () => {
|
||||
// Fails if the chart, which has no period filter of its own, ignores the page's periods or opens on an empty one of
|
||||
// them while an earlier one it was given has data.
|
||||
const vacio = (id: string) => payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id]),
|
||||
row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S1', '2025-S2', '2026-S1']);
|
||||
const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)]));
|
||||
expect(routeModel(data, 'semestre', ['2025-S1', '2026-S1', '2025-S2']).period).toBe('2025-S2');
|
||||
expect(routeModel(data, 'semestre', ['2025-S1']).period).toBe('2025-S1');
|
||||
expect(routeModel(data, 'semestre', ['2026-S1']).period).toBe('2026-S1');
|
||||
expect(routeModel(data, 'semestre', ['2023-S1']).period).toBe('2025-S2');
|
||||
});
|
||||
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
|
||||
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
|
||||
// becomes a bar or leaves a gap in the chain.
|
||||
|
||||
@@ -47,7 +47,8 @@ const fail = (message: string): never => { throw new RouteIncompatible(message);
|
||||
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
|
||||
|
||||
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo,
|
||||
requested?: string | readonly string[]): RouteModel {
|
||||
const boxes: Record<string, Record<string, Caja>> = {};
|
||||
for (const id of ROUTE_IDS) {
|
||||
const d = data[id];
|
||||
@@ -66,9 +67,12 @@ export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPerio
|
||||
}
|
||||
}
|
||||
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
|
||||
// Without a valid request the newest period that has a published box: a semester that has just begun is empty.
|
||||
// The newest of the requested periods (the page's filter) that has a published box, else the newest requested one;
|
||||
// without a valid request, the newest period that has a published box: a semester that has just begun is empty.
|
||||
const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado');
|
||||
const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0];
|
||||
const pedidos = (typeof requested === 'string' ? [requested] : [...(requested ?? [])])
|
||||
.filter(p => periods.includes(p)).sort().reverse();
|
||||
const period = pedidos.length ? pedidos.find(hasData) ?? pedidos[0] : periods.find(hasData) ?? periods[0];
|
||||
let cursor = 0;
|
||||
const rows = ROUTE_STEPS.map((step): RouteRow => {
|
||||
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
|
||||
@@ -4,9 +4,79 @@
|
||||
<button type="button" (click)="load()">Reintentar resumen</button>
|
||||
}
|
||||
@if (status() === 'ready' && detalle(); as d) {
|
||||
<div class="resumen" [class.sin-eeg]="!d.eeg">
|
||||
<section class="panel ados" aria-label="Resumen ADOS-2">
|
||||
<h3>ADOS-2</h3>
|
||||
@if (modo === 'tarjetas') {
|
||||
<div class="tarjetas">
|
||||
<section class="panel" aria-label="Resumen ADOS-2">
|
||||
<h3>ADOS-2</h3>
|
||||
@if (d.ados2; as a) {
|
||||
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
|
||||
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacionDe(a) }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
</div>
|
||||
@for (dom of a.dominios; track dom.codigo) {
|
||||
<div class="dominio">
|
||||
<span>{{ dom.etiqueta }} ({{ dom.codigo }})</span><span>{{ dom.puntaje }} / {{ dom.maximo }}</span>
|
||||
<span class="bar" aria-hidden="true"><span [style.width.%]="pct(dom.puntaje, dom.maximo)"></span></span>
|
||||
</div>
|
||||
}
|
||||
} @else { <p>Sin evaluación ADOS-2 registrada.</p> }
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-label="Calidad del EEG">
|
||||
<h3>Calidad del EEG</h3>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
|
||||
<small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG.' }}</small>
|
||||
</div>
|
||||
<p class="cifras">{{ reglasFuera(e) }} de {{ delEstudio(e).length }} reglas del estudio fuera de rango · {{ canalesMalos(e).length }} {{ canalesMalos(e).length === 1 ? 'canal descartado' : 'canales descartados' }}</p>
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ alteradas(e).length }} de {{ evaluables(e) }} métricas evaluadas fuera de la referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}).</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="alteradas">
|
||||
@for (m of alteradas(e); track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado"><span>{{ m.etiqueta }}</span><span class="estado">{{ estado[m.estado] }} · z = {{ cifras(m.valor_z) }}</span></li>
|
||||
}
|
||||
</ul>
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
@if (filasRelacion(rel); as filas) {
|
||||
@if (!filas.length) {
|
||||
<p class="sin-alteraciones">Ninguna zona alterada de este paciente tiene una asociación clara con el ADOS-2.</p>
|
||||
} @else {
|
||||
<p class="meta">{{ filas.length }} {{ filas.length === 1 ? 'asociación' : 'asociaciones' }} en zonas alteradas del paciente (modelo de {{ rel.n_cohorte }} niños).@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
<p class="principal"><strong>{{ filas[0].biomarcador }}</strong> · {{ filas[0].zona_etiqueta }} (z = {{ cifras(filas[0].valor_z) }}) con {{ filas[0].resultado_etiqueta }}:
|
||||
<span class="prob">{{ porcentaje(filas[0].probabilidad) }} %</span> de probabilidad, OR {{ cifras(filas[0].or) }}.</p>
|
||||
}
|
||||
}
|
||||
} @else { <p>Sin modelo de asociación disponible.</p> }
|
||||
</section>
|
||||
</div>
|
||||
<button type="button" class="completo" (click)="completo.emit(d.id_seudonimo)">Ver el resumen completo del paciente</button>
|
||||
} @else {
|
||||
<article class="documento" [attr.aria-label]="'Resumen del paciente ' + d.id_seudonimo">
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Datos del paciente</h2></summary>
|
||||
<dl>
|
||||
<dt>Identificador seudónimo</dt><dd>{{ d.id_seudonimo }}</dd>
|
||||
<dt>Grupo de edad</dt><dd>{{ d.grupo_edad || 'Sin dato' }}</dd>
|
||||
@if (d.eeg; as e) { <dt>Edad al EEG</dt><dd>{{ e.edad_meses ?? 'Sin dato' }}{{ e.edad_meses !== null && e.edad_meses !== undefined ? ' meses' : '' }}</dd> }
|
||||
</dl>
|
||||
</details>
|
||||
|
||||
<details class="seccion" open>
|
||||
<summary><h2>ADOS-2</h2></summary>
|
||||
@if (d.ados2; as a) {
|
||||
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||
<div class="headline">
|
||||
@@ -34,10 +104,10 @@
|
||||
</table>
|
||||
</details>
|
||||
} @else { <p>Sin evaluación ADOS-2 registrada.</p> }
|
||||
</section>
|
||||
</details>
|
||||
|
||||
<section class="panel calidad" aria-label="Calidad del EEG">
|
||||
<h3>Calidad del EEG</h3>
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Calidad del EEG</h2></summary>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
|
||||
<div class="headline">
|
||||
@@ -56,77 +126,74 @@
|
||||
</ul>
|
||||
}
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
</details>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
|
||||
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.referencia; as r) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
|
||||
} @else {
|
||||
<p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
|
||||
@if (d.eeg; as e) {
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h2></summary>
|
||||
<p class="meta">Referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}). Elige una alteración para ver sus zonas y la norma.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<div class="alteraciones-lado">
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-pressed]="m.estado === 'no_evaluable' ? null : mapaElegido === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.referencia; as r) {
|
||||
<p class="valor">{{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ cifras(r.min) }}–{{ cifras(r.max) }}@if (r.mediana !== null) { (mediana {{ cifras(r.mediana) }}) } · z = {{ cifras(m.valor_z) }}</p>
|
||||
} @else {
|
||||
<p class="valor">@if (m.valor !== null) { {{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
|
||||
}
|
||||
@if (m.efectos.length) {
|
||||
<p class="efectos-titulo">Posibles efectos asociados</p>
|
||||
<ul class="efectos">
|
||||
@for (efecto of m.efectos; track efecto) { <li>{{ efecto }}</li> }
|
||||
</ul>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
@if (m.efectos.length) {
|
||||
<p class="efectos-titulo">Posibles efectos asociados</p>
|
||||
<ul class="efectos">
|
||||
@for (efecto of m.efectos; track efecto) { <li>{{ efecto }}</li> }
|
||||
</ul>
|
||||
</ul>
|
||||
<section class="graficos" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (!abierto(e)) { <p class="sin-grafico">La métrica elegida no tiene mapa ni norma por edad para mostrar.</p> }
|
||||
@if (mapaActual(e); as mapa) {
|
||||
<div class="grafico">
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@if (figura) {
|
||||
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'260px'"
|
||||
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
|
||||
@for (r of mapa.regiones; track r.codigo) {
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ cifras(r.valor_z) }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
</div>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@if (abierto(e)) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (mapaActual(e) && normaActual(e)) {
|
||||
<div class="vistas" role="group" aria-label="Qué mostrar">
|
||||
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
|
||||
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
|
||||
@if (normaActual(e); as m) {
|
||||
<div class="grafico">
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ cifras(m.valor_z) }}).</p>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@if (vista === 'norma' && normaActual(e); as m) {
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).</p>
|
||||
} @else if (mapaActual(e); as mapa) {
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@if (figura) {
|
||||
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'260px'"
|
||||
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
|
||||
@for (r of mapa.regiones; track r.codigo) {
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
}
|
||||
</section></div>
|
||||
</details>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h2></summary>
|
||||
<p class="meta">Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se
|
||||
asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2.
|
||||
No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
@@ -144,9 +211,9 @@
|
||||
<tbody>
|
||||
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
|
||||
<tr [class.alterada]="zonaAlterada(f)">
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ cifras(f.valor_z) }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
|
||||
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td><span class="or">OR {{ cifras(f.or) }}</span><small>IC 95 % {{ cifras(f.ic_inf) }}–{{ cifras(f.ic_sup) }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td>
|
||||
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
|
||||
<span class="barra" aria-hidden="true">
|
||||
@@ -165,7 +232,8 @@
|
||||
probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0.
|
||||
Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</article>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
:host { display: block; container: host / inline-size; }
|
||||
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; }
|
||||
// The four cards side by side in one row; two by two and then stacked as the row narrows.
|
||||
.tarjetas { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .75rem; }
|
||||
@container host (max-width: 64rem) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@container host (max-width: 36rem) { .tarjetas { grid-template-columns: minmax(0, 1fr); } }
|
||||
.cifras { margin: 0; font-size: .85rem; }
|
||||
.alteradas { margin: 0; padding: 0; list-style: none; font-size: .85rem; }
|
||||
.alteradas li { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; padding: .25rem 0; border-top: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.alteradas .estado { color: #B3261E; font-weight: 400; }
|
||||
.principal { margin: 0; font-size: .85rem; }
|
||||
button.completo { margin-top: .75rem; padding: .35rem .75rem; color: var(--issste-accent); font-weight: 600; }
|
||||
// The full record: one collapsible section after another, no cards.
|
||||
.documento { max-width: 64rem; }
|
||||
.seccion { margin: 0; padding: .25rem 0 .75rem; border-bottom: 1px solid var(--issste-border); }
|
||||
.seccion > summary { margin: 0; }
|
||||
.seccion > summary h2 { margin: 0; font-size: 1.15rem; }
|
||||
.seccion > :not(summary) { margin-inline-start: 1.25rem; }
|
||||
.documento .metricas { grid-template-columns: minmax(0, 1fr); gap: 0; }
|
||||
.documento .metricas > li { border: 0; border-top: 1px solid var(--issste-border); border-radius: 0; padding: .5rem 0 .5rem .6rem; }
|
||||
.documento .metricas > li[data-estado=aumentado], .documento .metricas > li[data-estado=disminuido] { border-inline-start: 4px solid #B3261E; }
|
||||
.panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); }
|
||||
h3 { margin: 0 0 .15rem; font-size: 1rem; }
|
||||
.meta { margin: 0 0 .5rem; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
@@ -47,17 +65,12 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
|
||||
font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; }
|
||||
.sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; }
|
||||
.metricas, .efectos { margin: 0; padding: 0; list-style: none; }
|
||||
// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it.
|
||||
.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; }
|
||||
.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; }
|
||||
.marco-mapa { min-width: 0; overflow: hidden; }
|
||||
.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; }
|
||||
.mapa h3 { margin-top: 0; }
|
||||
@keyframes aparecer { from { opacity: 0; } }
|
||||
@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } }
|
||||
@container host (max-width: 42rem) { .mapa { width: 100cqw; } }
|
||||
@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } }
|
||||
@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } }
|
||||
// The full summary: the metric list on the left, the plots of the chosen metric on the right, always in view.
|
||||
.alteraciones-lado { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); gap: 1.5rem; align-items: start }
|
||||
@container host (max-width: 52rem) { .alteraciones-lado { grid-template-columns: minmax(0, 1fr); } }
|
||||
.graficos { min-width: 0; display: grid; gap: 1rem; }
|
||||
.grafico h3 { margin-top: 0; }
|
||||
.sin-grafico { margin: 0; font-size: .9rem; color: var(--issste-text-secondary); }
|
||||
.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; }
|
||||
.metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; }
|
||||
.metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); }
|
||||
@@ -65,7 +78,9 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
|
||||
.metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; }
|
||||
.metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; }
|
||||
li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; }
|
||||
li[data-estado=normal] .estado { color: var(--issste-text-secondary); font-weight: 400; }
|
||||
li[data-estado=normal] .estado { color: #1B7F3B; font-weight: 600; }
|
||||
:host-context([data-theme=dark]) li[data-estado=normal] .estado { color: #6FD38A; }
|
||||
@media (prefers-color-scheme: dark) { :host-context(:root:not([data-theme=light])) li[data-estado=normal] .estado { color: #6FD38A; } }
|
||||
li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font-weight: 400; font-style: italic; }
|
||||
.valor { margin: .1rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); font-variant-numeric: tabular-nums; }
|
||||
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
|
||||
@@ -88,9 +103,4 @@ button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border
|
||||
.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); }
|
||||
.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); }
|
||||
.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); }
|
||||
// The switch between the head map and the age norm, when the metric has both.
|
||||
.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; }
|
||||
.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; }
|
||||
.vistas button + button { border-inline-start: 1px solid var(--issste-border); }
|
||||
.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; }
|
||||
.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core';
|
||||
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, output, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
@@ -85,7 +85,13 @@ export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
|
||||
styleUrl: './tea-paciente-resumen.scss',
|
||||
})
|
||||
export class TeaPacienteResumen implements OnInit {
|
||||
@Input({ required: true }) id = '';
|
||||
@Input() id = '';
|
||||
/** A summary the host already has (an analysis that was not stored): nothing is requested. */
|
||||
@Input() detalleInicial?: TeaPacienteDetalle;
|
||||
/** `tarjetas`: four summary cards for a table row. `resumen`: the whole record as a summary with collapsible headers. */
|
||||
@Input() modo: 'tarjetas' | 'resumen' = 'tarjetas';
|
||||
/** The cards' button: the host shows the whole record in its own section. */
|
||||
readonly completo = output<string>();
|
||||
private readonly service = inject(TeaSeguimientoService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
@@ -101,8 +107,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
}
|
||||
return '#FFFFFF';
|
||||
}
|
||||
// The side panel shows the chosen metric's head map, its age norm, or both with a switch between them.
|
||||
vista: 'zonas' | 'norma' = 'zonas';
|
||||
// The chosen metric's head map and its age norm, whichever it has.
|
||||
figuraNorma?: PlotlyFigure;
|
||||
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||||
// The age norm can only be drawn with the curve, the patient's value and their age.
|
||||
@@ -115,37 +120,38 @@ export class TeaPacienteResumen implements OnInit {
|
||||
private mostrar(eeg: TeaEeg, codigo: string | undefined) {
|
||||
const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo);
|
||||
this.mapaElegido = mapa || norma ? codigo : undefined;
|
||||
this.vista = mapa ? 'zonas' : 'norma';
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
|
||||
}
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the panel again, and the cards take the whole space back.
|
||||
this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo);
|
||||
// In the cards' accordion the chosen metric closes its panel again; in the full summary the plots stay in view.
|
||||
this.mostrar(eeg, this.modo === 'tarjetas' && codigo === this.mapaElegido ? undefined : codigo);
|
||||
}
|
||||
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
|
||||
readonly clasificacion = CLASIFICACIONES_ADOS2;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
readonly estado = ESTADO;
|
||||
ngOnInit() { this.load(); }
|
||||
ngOnInit() { if (this.detalleInicial) this.aplicar(this.detalleInicial); else this.load(); }
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
private aplicar(d: TeaPacienteDetalle) {
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
}
|
||||
load() {
|
||||
this.status.set('loading');
|
||||
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: d => {
|
||||
// Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered.
|
||||
const e = d.eeg;
|
||||
if (e) {
|
||||
const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo));
|
||||
this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo);
|
||||
} else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; }
|
||||
this.detalle.set(d); this.status.set('ready');
|
||||
},
|
||||
next: d => this.aplicar(d),
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
// The study-wide checks, then each bad channel.
|
||||
delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); }
|
||||
// Three significant digits, without trailing zeros.
|
||||
cifras(n: number | null | undefined) { return typeof n === 'number' ? String(Number(n.toPrecision(3))) : ''; }
|
||||
canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); }
|
||||
valorDe(c: TeaCriterioCalidad) {
|
||||
return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor;
|
||||
@@ -155,6 +161,9 @@ export class TeaPacienteResumen implements OnInit {
|
||||
return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.';
|
||||
}
|
||||
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
|
||||
// How many of the study-wide checks are out of range, and how many metrics could be judged against the age norm.
|
||||
reglasFuera(eeg: TeaEeg) { return this.delEstudio(eeg).filter(c => c.nivel === 'malo').length; }
|
||||
evaluables(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado !== 'no_evaluable').length; }
|
||||
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
|
||||
@@ -165,7 +174,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad';
|
||||
}
|
||||
porcentaje(p: number) { return Math.round(100 * p); }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${this.cifras(q)}`; }
|
||||
observado(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return 'Sin dato';
|
||||
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
|
||||
|
||||
@@ -13,9 +13,9 @@ const listo = (value: string | number, period = '2025-S2'): Result => ({ state:
|
||||
const c1 = (value: string, numerador: number, denominador: number): Result => ({ ...listo(value), numerador, denominador });
|
||||
|
||||
describe('Resumen TEA por periodo', () => {
|
||||
function render(paneles: IndicadorKpiPanel[]) {
|
||||
function render(paneles: IndicadorKpiPanel[], periodo = '2025-S2') {
|
||||
const fixture = TestBed.createComponent(TeaResumenPeriodo);
|
||||
fixture.componentRef.setInput('periodo', '2025-S2'); fixture.componentRef.setInput('paneles', paneles);
|
||||
fixture.componentRef.setInput('periodo', periodo); fixture.componentRef.setInput('paneles', paneles);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
@@ -27,9 +27,9 @@ describe('Resumen TEA por periodo', () => {
|
||||
panel('M21_diagnosticados_con_eeg', c1('71.9', 41, 57)), panel('M22_diagnosticados_sin_eeg', c1('28.1', 16, 57)),
|
||||
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14)),
|
||||
panel('M29_calidad_eeg', { ...listo(80), categorias: { BUENO: 20, MALO: 50, SIN_ANALIZAR: 10 } })];
|
||||
const texto = (root: HTMLElement) => root.textContent!.replace(/\s+/g, ' ');
|
||||
const texto = (root: HTMLElement) => Array.from(root.querySelectorAll('p'), p => p.textContent!.replace(/\s+/g, ' ').trim()).join(' ');
|
||||
|
||||
it('redacta los dos párrafos con cada población y resalta los valores', () => {
|
||||
it('identifica el denominador de cada medida y resalta los valores publicados', () => {
|
||||
// Fails if a sentence reads another indicator's figure, if the stages stop adding up to the children evaluated
|
||||
// or if a median is cut (22.5 stays 22.5).
|
||||
const root: HTMLElement = render(completos()).nativeElement;
|
||||
@@ -37,11 +37,12 @@ describe('Resumen TEA por periodo', () => {
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. 50 estudios de EEG no son aceptables para un análisis.');
|
||||
expect(text).toContain('*tomando la mediana de los tiempos');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '25.0%']);
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '50']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
expect(root.querySelector('h2')!.textContent).toBe('Resumen');
|
||||
});
|
||||
|
||||
it('no copia cifras de ejemplo: otros conteos cambian toda la redacción', () => {
|
||||
@@ -50,24 +51,34 @@ describe('Resumen TEA por periodo', () => {
|
||||
panel('M28_casos_por_estado', { ...listo(3), categorias: { EEG: 0, SOLO_MCHAT: 1, PSICOLOGIA: 1, NEUROPEDIATRIA: 1 } }),
|
||||
panel('M24_confirmacion_diagnostico', c1('50.0', 1, 2)), panel('M25_dias_mchat_diagnostico', listo(31)),
|
||||
panel('M21_diagnosticados_con_eeg', c1('0.0', 0, 1)), panel('M22_diagnosticados_sin_eeg', c1('100.0', 1, 1)),
|
||||
panel('M26_dias_mchat_ados2', listo(5)), panel('M27_dias_ados2_diagnostico', listo(9)),
|
||||
panel('M26_dias_mchat_ados2', listo(54.5)), panel('M27_dias_ados2_diagnostico', listo(9)),
|
||||
panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })];
|
||||
const text = texto(render(paneles).nativeElement);
|
||||
const periodo = '2026-03';
|
||||
for (const p of paneles) p.result.set({ ...p.result(), period: periodo });
|
||||
const text = texto(render(paneles, periodo).nativeElement);
|
||||
expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. 1 estudios de EEG no son aceptables para un análisis.');
|
||||
for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo);
|
||||
});
|
||||
|
||||
it('un cero publicado es un cero y la ausencia de estudios no inventa un porcentaje', () => {
|
||||
// Fails if a published 0 turns into «sin dato», or if 0 studies print a percentage of buena calidad.
|
||||
// Fails if a published 0 turns into «sin dato», or if 0 studies print a count other than 0.
|
||||
const paneles = completos();
|
||||
paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57));
|
||||
paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. 0 estudios de EEG no son aceptables para un análisis.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0');
|
||||
});
|
||||
|
||||
it('incluye los estudios sin analizar en el total de EEG del periodo', () => {
|
||||
// Fails if the share of good quality leaves the unanalysed studies out of its denominator.
|
||||
const paneles = completos();
|
||||
paneles[7].result.set({ ...listo(6), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 6 } });
|
||||
expect(texto(render(paneles).nativeElement))
|
||||
.toContain('0 estudios de EEG no son aceptables para un análisis.');
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
// Fails if a suppressed, foreign-period or unpublished figure is drawn as a number, or if its reason is lost.
|
||||
const paneles = completos();
|
||||
@@ -75,10 +86,18 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[2].result.set(listo(30, '2025-S1'));
|
||||
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M29_calidad_eeg')).nativeElement;
|
||||
const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato'));
|
||||
expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']);
|
||||
expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Sin datos para el periodo seleccionado', 'Indicador no publicado']);
|
||||
expect(root.textContent).not.toContain('30 días');
|
||||
});
|
||||
|
||||
it('una respuesta de otro periodo no invalida los conteos vigentes de M21', () => {
|
||||
const paneles = completos();
|
||||
paneles[4].result.set({ ...c1('28.1', 16, 58), period: '2025-S1' });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG');
|
||||
expect(root.querySelector('.dato.sin-dato')?.getAttribute('title')).toBe('Sin datos para el periodo seleccionado');
|
||||
});
|
||||
|
||||
it('no muestra los conteos de M21 y M22 si no hablan de los mismos niños', () => {
|
||||
// Fails if the confirmed children of M21 and of M22 disagree and the summary still prints them as one population.
|
||||
const paneles = completos();
|
||||
|
||||
@@ -2,8 +2,7 @@ import { NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { shareNumber } from './indicadores-format';
|
||||
import { M28_COMPLETO, M29_BUENO } from './indicadores-kpi';
|
||||
import { M28_COMPLETO, M29_MALO } from './indicadores-kpi';
|
||||
|
||||
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
|
||||
|
||||
@@ -16,7 +15,8 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
selector: 'app-tea-resumen-periodo',
|
||||
imports: [MatButtonModule, NgTemplateOutlet],
|
||||
template: `
|
||||
<article class="resumen" [attr.aria-busy]="cargando">
|
||||
<article class="resumen" [attr.aria-busy]="cargando" aria-labelledby="tea-resumen-titulo">
|
||||
<h2 id="tea-resumen-titulo">Resumen</h2>
|
||||
<p>
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños entre 16 y 36 meses;
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> únicamente tienen M-CHAT,
|
||||
@@ -29,11 +29,10 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
<br>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado al cierre del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEeg() }" /> tienen un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEeg() }" /> aún no cuentan con uno de esa calidad.
|
||||
Del total de estudios de EEG del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado en este periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> presentan estudio de EEG y faltan
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> por realizarlo.
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: eegNoAceptables() }" /> estudios de EEG no son aceptables para un análisis.
|
||||
</p>
|
||||
<p class="nota">*tomando la mediana de los tiempos</p>
|
||||
@if (conError.length) {
|
||||
@@ -48,6 +47,7 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
:host { display: block; min-width: 0; }
|
||||
.resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0 0 var(--issste-space-3); font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; }
|
||||
p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; }
|
||||
p + p { margin-top: var(--issste-space-4); }
|
||||
p.nota { margin-top: var(--issste-space-2); font-size: .95rem; line-height: 1.5; color: var(--issste-text-secondary); }
|
||||
@@ -70,8 +70,9 @@ export class TeaResumenPeriodo {
|
||||
if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' };
|
||||
if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' };
|
||||
// Never show a value from another period in a sentence about this one.
|
||||
if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo)
|
||||
if (result.state !== 'Disponible' || result.value === undefined)
|
||||
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
|
||||
if (result.period !== this.periodo) return this.sinDato('Sin datos para el periodo seleccionado');
|
||||
return undefined;
|
||||
}
|
||||
private sinDato(detalle: string): Valor { return { texto: 'sin dato', estado: 'sin_dato', detalle }; }
|
||||
@@ -90,6 +91,7 @@ export class TeaResumenPeriodo {
|
||||
}
|
||||
// M21 and M22 split the same confirmed children, so a count of either is only shown while their denominators agree.
|
||||
private poblacionComun(): boolean {
|
||||
if (this.fallo(M21) || this.fallo(M22)) return true;
|
||||
const a = this.panel(M21)?.result(), b = this.panel(M22)?.result();
|
||||
return !(a?.denominador !== undefined && b?.denominador !== undefined && a.denominador !== b.denominador);
|
||||
}
|
||||
@@ -103,15 +105,14 @@ export class TeaResumenPeriodo {
|
||||
// Children with a confirmed diagnosis at the period's end, the denominator of M21 and M22.
|
||||
confirmados() { return this.conteo(M21, 'denominador'); }
|
||||
// Of them, those with a good EEG (M21's numerator) and those without yet (M22's).
|
||||
conEeg() { return this.conteo(M21, 'numerador'); }
|
||||
sinEeg() { return this.conteo(M22, 'numerador'); }
|
||||
// The share of the period's EEGs (M29 counts exams, not patients) the analysis found valid.
|
||||
buenaCalidad(): Valor {
|
||||
conEegBueno() { return this.conteo(M21, 'numerador'); }
|
||||
sinEegBueno() { return this.conteo(M22, 'numerador'); }
|
||||
// The period's EEGs (M29 counts exams, not patients) the analysis found not valid.
|
||||
eegNoAceptables(): Valor {
|
||||
const base = this.valor(M29, '');
|
||||
if (base.estado !== 'listo') return base;
|
||||
const result = this.panel(M29)!.result(), total = Number(result.value), buenos = result.categorias?.[M29_BUENO];
|
||||
if (total === 0) return this.sinDato('Sin estudios de EEG en el periodo');
|
||||
return buenos === undefined ? this.sinDato('Categoría no publicada') : { texto: shareNumber(buenos, total) + '%', estado: 'listo' };
|
||||
const malos = this.panel(M29)!.result().categorias?.[M29_MALO];
|
||||
return malos === undefined ? this.sinDato('Categoría no publicada') : { texto: String(malos), estado: 'listo' };
|
||||
}
|
||||
get cargando() { return this.paneles.some(p => p.result().loading); }
|
||||
get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); }
|
||||
|
||||
@@ -35,7 +35,8 @@ const CRITERIOS = 'urn:tea:validation';
|
||||
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
|
||||
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { 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 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<string, [number, number]> = {
|
||||
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],
|
||||
@@ -43,7 +44,8 @@ export const ELECTRODOS: Record<string, [number, number]> = {
|
||||
};
|
||||
const REGIONES: [string, string, string[]][] = [
|
||||
['frontal_izq', 'Frontal izquierda', ['Fp1', 'F3', 'F7']], ['frontal_der', 'Frontal derecha', ['Fp2', 'F4', 'F8']],
|
||||
['central', 'Central', ['Fz', 'C3', 'Cz', 'C4']], ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']],
|
||||
['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);
|
||||
@@ -329,19 +331,26 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
return forkJoin({
|
||||
bundle: this.client.get<Bundle>(`/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);
|
||||
}));
|
||||
}).pipe(map(({ bundle, metricas }) => detalleDeBundle(bundle, metricas, id)));
|
||||
}
|
||||
// The summary of an analysis the server did without storing it, read like a stored patient's.
|
||||
override vistaPrevia(bundle: unknown, id = 'vista-previa') {
|
||||
return this.metricas().pipe(map(metricas => detalleDeBundle(bundle as Bundle, metricas, id)));
|
||||
}
|
||||
}
|
||||
|
||||
// A `$resumen-tea` bundle as the patient summary the view draws.
|
||||
function detalleDeBundle(bundle: Bundle, metricas: Metric[], id: string) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { map, Observable, throwError } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
|
||||
@@ -244,4 +244,8 @@ export class TeaSeguimientoService {
|
||||
detalle(id: string) {
|
||||
return this.http.get<unknown>(`/tea/seguimiento/${encodeURIComponent(id)}`).pipe(map(v => teaPacienteDetalle(v, id)));
|
||||
}
|
||||
/** The summary of an analysis that was not stored; only the FHIR service reads the server's bundle. */
|
||||
vistaPrevia(_bundle: unknown, _id?: string): Observable<TeaPacienteDetalle> {
|
||||
return throwError(() => new Error('La vista previa necesita el servicio FHIR.'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service';
|
||||
import { mapaFigure } from './tea-paciente-resumen';
|
||||
import { mapaFigure, TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
|
||||
@@ -57,6 +57,16 @@ describe('Seguimiento TEA', () => {
|
||||
return fixture;
|
||||
}
|
||||
const request = () => http.expectOne(r => r.url === '/tea/seguimiento');
|
||||
// The patient's whole record, as the window opened from the patient id shows it.
|
||||
function resumen(d: object, id = 'T-0001') {
|
||||
const fixture = TestBed.createComponent(TeaPacienteResumen);
|
||||
fixture.componentRef.setInput('id', id); fixture.componentRef.setInput('modo', 'resumen');
|
||||
fixture.detectChanges();
|
||||
http.expectOne(`/tea/seguimiento/${id}`).flush(d); fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
const seccion = (root: HTMLElement, titulo: string) =>
|
||||
Array.from(root.querySelectorAll<HTMLDetailsElement>('details.seccion')).find(d => d.querySelector('summary h2')!.textContent!.trim().startsWith(titulo))!;
|
||||
it('muestra las siete columnas y los valores ausentes como No disponible', () => {
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
@@ -146,17 +156,15 @@ describe('Seguimiento TEA', () => {
|
||||
expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' });
|
||||
http.verify();
|
||||
});
|
||||
it('abre con las zonas de la primera alteración, cambia al elegir otra y se cierra al repetirla', () => {
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
it('el resumen muestra las alteraciones y sus gráficas lado a lado, siempre a la vista: elegir otra las cambia y repetirla las deja', () => {
|
||||
const fixture = resumen(detalle);
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
const lado = root.querySelector('.alteraciones-lado')!;
|
||||
expect(lado.querySelector('ul.metricas')).not.toBeNull();
|
||||
expect(lado.querySelector('section.graficos')).not.toBeNull();
|
||||
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true);
|
||||
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true');
|
||||
const panel = () => root.querySelector('section.mapa')!;
|
||||
expect(panel().classList.contains('panel')).toBe(false);
|
||||
const panel = () => root.querySelector('section.graficos')!;
|
||||
expect(tarjetas[0].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(panel().textContent).toContain('Azul: menos actividad');
|
||||
expect(panel().textContent).toContain('Rojo: más actividad');
|
||||
expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior');
|
||||
@@ -164,45 +172,38 @@ describe('Seguimiento TEA', () => {
|
||||
tarjetas[3].click(); fixture.detectChanges();
|
||||
expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos');
|
||||
expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital');
|
||||
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false');
|
||||
expect(tarjetas[0].getAttribute('aria-pressed')).toBe('false');
|
||||
expect(tarjetas[1].disabled).toBe(true);
|
||||
expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false);
|
||||
expect(tarjetas[1].hasAttribute('aria-pressed')).toBe(false);
|
||||
// Choosing the same metric again keeps its plots in view.
|
||||
tarjetas[3].click(); fixture.detectChanges();
|
||||
expect(root.querySelector('section.mapa')).toBeNull();
|
||||
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false);
|
||||
tarjetas[0].click(); fixture.detectChanges();
|
||||
expect(root.querySelector('section.mapa')).not.toBeNull();
|
||||
expect(panel().querySelector('.regiones')).not.toBeNull();
|
||||
expect(tarjetas[3].getAttribute('aria-pressed')).toBe('true');
|
||||
http.verify();
|
||||
});
|
||||
it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
|
||||
it('muestra el mapa y la norma por edad juntos cuando la métrica tiene los dos, o solo la norma si no tiene mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
|
||||
const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48],
|
||||
p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] };
|
||||
const conCurva = detalle.eeg.alteraciones.map(m =>
|
||||
m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m);
|
||||
const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } };
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const fixture = resumen(conNorma);
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges();
|
||||
const panel = () => root.querySelector('section.mapa')!;
|
||||
const vistas = () => panel().querySelectorAll<HTMLButtonElement>('.vistas button');
|
||||
// Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age.
|
||||
expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']);
|
||||
expect(panel().textContent).toContain('Zonas más afectadas');
|
||||
vistas()[1].click(); fixture.detectChanges();
|
||||
expect(vistas()[1].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad');
|
||||
const panel = () => root.querySelector('section.graficos')!;
|
||||
const titulos = () => Array.from(panel().querySelectorAll('h3')).map(h => h.textContent);
|
||||
// Ritmo has both: the map and the norm show together, with the patient's value and age, and no switch between them.
|
||||
expect(titulos()).toEqual(['Zonas más afectadas', 'Norma por edad']);
|
||||
expect(panel().querySelector('.vistas')).toBeNull();
|
||||
expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)');
|
||||
expect(panel().querySelector('.regiones')).toBeNull();
|
||||
// Gradiente has no map: its card opens the norm alone, without the switch.
|
||||
expect(panel().querySelector('.regiones')).not.toBeNull();
|
||||
// Gradiente has no map: its norm shows alone.
|
||||
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||
tarjetas[4].click(); fixture.detectChanges();
|
||||
expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true');
|
||||
expect(vistas().length).toBe(0);
|
||||
expect(tarjetas[4].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(titulos()).toEqual(['Norma por edad']);
|
||||
expect(panel().textContent).toContain('Gradiente anteroposterior');
|
||||
const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance;
|
||||
const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[];
|
||||
const c = fixture.componentInstance;
|
||||
const trazas = c.figuraNorma!.data as { name: string; x: number[]; y: number[] }[];
|
||||
expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']);
|
||||
expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]);
|
||||
const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m);
|
||||
@@ -215,14 +216,55 @@ describe('Seguimiento TEA', () => {
|
||||
expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)');
|
||||
expect(marco()).toBe('#FFFFFF');
|
||||
});
|
||||
it('redondea a tres cifras significativas', () => {
|
||||
// Fails if the alterations show more than three significant digits or keep trailing zeros.
|
||||
const c = TestBed.createComponent(TeaPacienteResumen).componentInstance;
|
||||
expect([c.cifras(0.123456), c.cifras(12.3456), c.cifras(1234.5), c.cifras(2), c.cifras(null)]).toEqual(['0.123', '12.3', '1230', '2', '']);
|
||||
});
|
||||
|
||||
it('sin alteraciones abre con la primera métrica evaluable', () => {
|
||||
const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m);
|
||||
const fixture = resumen({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } });
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('section.graficos .meta')!.textContent).toContain('Ritmo posterior');
|
||||
http.verify();
|
||||
});
|
||||
it('el identificador abre el resumen completo en su propia sección, sin desplegar la fila, y Volver regresa a la lista', () => {
|
||||
const fixture = open();
|
||||
const ficha = vi.fn(); fixture.componentInstance.fichaPacienteAbierta.subscribe(ficha);
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m);
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); fixture.detectChanges();
|
||||
expect(root.querySelector('section.mapa .meta')!.textContent).toContain('Ritmo posterior');
|
||||
const id = root.querySelector<HTMLButtonElement>('tbody tr.tea-row button.patient-link')!;
|
||||
expect(id.textContent!.trim()).toBe('T-0001');
|
||||
id.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
expect(ficha).toHaveBeenLastCalledWith(true);
|
||||
expect(root.querySelector('tr.tea-detalle')).toBeNull();
|
||||
const seccionFicha = root.querySelector('section.ficha-tea')!;
|
||||
expect(seccionFicha.querySelector('h2')!.textContent).toContain('T-0001');
|
||||
expect(seccionFicha.querySelectorAll('details.seccion').length).toBeGreaterThanOrEqual(4);
|
||||
expect(root.querySelector<HTMLElement>('form')!.closest('[hidden]')).not.toBeNull();
|
||||
Array.from(seccionFicha.querySelectorAll('button')).find(b => b.textContent!.includes('Volver a Seguimiento'))!.click(); fixture.detectChanges();
|
||||
expect(ficha).toHaveBeenLastCalledWith(false);
|
||||
expect(root.querySelector('section.ficha-tea')).toBeNull();
|
||||
expect(root.querySelector<HTMLElement>('form')!.closest('[hidden]')).toBeNull();
|
||||
expect(root.querySelectorAll('tbody tr.tea-row')).toHaveLength(2);
|
||||
http.verify();
|
||||
});
|
||||
it('el resumen completo son secciones con encabezado plegable, abiertas, y los reactivos van plegados dentro del ADOS-2', () => {
|
||||
const root: HTMLElement = resumen(detalle).nativeElement;
|
||||
const secciones = Array.from(root.querySelectorAll<HTMLDetailsElement>('details.seccion'));
|
||||
expect(secciones.map(d => d.querySelector('summary h2')!.textContent!.replace('Datos de ejemplo', '').trim())).toEqual(
|
||||
['Datos del paciente', 'ADOS-2', 'Calidad del EEG', 'Alteraciones del EEG']);
|
||||
expect(secciones.every(d => d.open)).toBe(true);
|
||||
expect(root.querySelector('.tarjetas, .panel')).toBeNull();
|
||||
expect(seccion(root, 'Datos del paciente').textContent).toContain('T-0001');
|
||||
expect(seccion(root, 'Datos del paciente').textContent).toContain('16-23 meses');
|
||||
const reactivos = seccion(root, 'ADOS-2').querySelector<HTMLDetailsElement>('details:not(.seccion)')!;
|
||||
expect(reactivos.open).toBe(false);
|
||||
expect(reactivos.textContent).toContain('A2 · Reactivo A2');
|
||||
secciones[1].open = false;
|
||||
expect(secciones[1].open).toBe(false);
|
||||
http.verify();
|
||||
});
|
||||
it('sin filtros no envía sus parámetros', () => {
|
||||
@@ -258,22 +300,24 @@ describe('Seguimiento TEA', () => {
|
||||
expect(toggles[1].getAttribute('aria-expanded')).toBe('true');
|
||||
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges();
|
||||
const panel = root.querySelector('#tea-detalle-T-0002')!;
|
||||
// Four summary cards, two by two, with the verdicts and no maps or item tables.
|
||||
expect(Array.from(panel.querySelectorAll('.tarjetas > section')).map(c => c.getAttribute('aria-label'))).toEqual([
|
||||
'Resumen ADOS-2', 'Calidad del EEG', 'Alteraciones del EEG', 'Relación de las alteraciones del EEG con el ADOS-2']);
|
||||
expect(panel.textContent).toContain('CSS 3');
|
||||
expect(panel.textContent).toContain('Afecto social (AS)');
|
||||
expect(panel.textContent).toContain('Válido');
|
||||
// Opens with the map of the first altered metric.
|
||||
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
// Item scores start collapsed.
|
||||
expect(panel.querySelector<HTMLDetailsElement>('details')!.open).toBe(false);
|
||||
expect(panel.querySelector('app-plotly-chart')).toBeNull();
|
||||
expect(panel.querySelector('details')).toBeNull();
|
||||
const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!;
|
||||
expect(metricas.textContent).toContain('Datos de ejemplo');
|
||||
expect(metricas.textContent).toContain('1 de 4 métricas evaluadas fuera de la referencia');
|
||||
expect(metricas.textContent).toContain('Ritmo posterior');
|
||||
expect(metricas.textContent).toContain('Disminuido');
|
||||
expect(metricas.textContent).toContain('Posibles efectos asociados');
|
||||
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(metricas.textContent).toContain('No se pudo medir en el estudio.');
|
||||
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual(
|
||||
['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']);
|
||||
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
|
||||
expect(metricas.textContent).not.toContain('Husos de sueño N3');
|
||||
expect(panel.querySelector('[aria-label="Calidad del EEG"]')!.textContent).toContain('1 de 2 reglas del estudio fuera de rango · 1 canal descartado');
|
||||
// The whole record opens in its own section from the patient id and from the cards' button.
|
||||
const enlace = panel.querySelector<HTMLButtonElement>('button.completo')!;
|
||||
expect(enlace.textContent).toContain('resumen completo');
|
||||
(root.querySelectorAll('tbody tr.tea-row')[2] as HTMLElement).click(); fixture.detectChanges();
|
||||
expect(root.querySelector('#tea-detalle-T-0002')).toBeNull();
|
||||
http.expectOne('/tea/seguimiento/T-0004').flush({ ...detalle, id_seudonimo: 'T-0004', ados2: null, eeg: null }); fixture.detectChanges();
|
||||
@@ -345,12 +389,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
|
||||
});
|
||||
it('la calidad es el veredicto del análisis, con sus reglas y los canales descartados, y se valida', () => {
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
const panel = root.querySelector('section.calidad')!;
|
||||
const panel = seccion(resumen(detalle).nativeElement, 'Calidad del EEG');
|
||||
const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim();
|
||||
expect(texto(panel.querySelector('.css')!)).toBe('Válido');
|
||||
expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']);
|
||||
@@ -381,8 +420,8 @@ describe('Seguimiento TEA', () => {
|
||||
});
|
||||
// The association model's panel (prototype, simulated data): the field is optional and checked when present.
|
||||
it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => {
|
||||
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa',
|
||||
resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
|
||||
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'CSS',
|
||||
resultado_etiqueta: 'Puntaje de severidad calibrado (CSS)', evento: '>=8', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
|
||||
probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 };
|
||||
const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 };
|
||||
const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } });
|
||||
@@ -392,12 +431,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow();
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges();
|
||||
const filas = Array.from(root.querySelectorAll('section.relacion tbody tr'));
|
||||
const filas = Array.from(seccion(resumen(rel([otra, fila])).nativeElement, 'Relación con el ADOS-2').querySelectorAll('tbody tr'));
|
||||
expect(filas.length).toBe(1);
|
||||
expect(filas[0].classList.contains('alterada')).toBe(true);
|
||||
expect(filas[0].textContent).toContain('q < 0.001');
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
<header><h1>Trastorno del espectro autista</h1><p>Explora los indicadores de trastorno del espectro autista.</p></header>
|
||||
<nav class="domain-nav" aria-label="Dominios de indicadores"><a routerLink="/indicadores/cacu">Cáncer cervicouterino</a><a routerLink="/indicadores/cama">Cáncer de mama</a><a routerLink="/indicadores/tea" aria-current="page">Trastorno del espectro autista</a></nav>
|
||||
<nav class="tabs" aria-label="Secciones de trastorno del espectro autista">
|
||||
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Resumen</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Histórico</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Indicadores</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Trazabilidad</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Análisis de Riesgo</button>
|
||||
</nav>
|
||||
@if (section() !== 'seguimiento') {
|
||||
<section aria-label="Consulta de indicadores">
|
||||
<h2>{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}</h2>
|
||||
<h2>{{ section() === 'resumen' ? 'Indicadores' : 'Trazabilidad' }}</h2>
|
||||
<form (ngSubmit)="section() === 'resumen' ? loadSummary() : loadHistory()">
|
||||
@if (section() === 'resumen') { <label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1"></label> }
|
||||
@else {
|
||||
@@ -30,8 +30,8 @@
|
||||
}
|
||||
</section>
|
||||
}
|
||||
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Seguimiento">
|
||||
<h2>Seguimiento</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
|
||||
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Análisis de Riesgo">
|
||||
<h2>Análisis de Riesgo</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
|
||||
<form (ngSubmit)="applyFilters()" class="filters">
|
||||
<label>Desde <input type="date" name="desde" [(ngModel)]="filters.since"></label><label>Fecha de corte <input type="date" name="corte" [(ngModel)]="filters.cutoff"></label>
|
||||
<label>Estado <select name="status" [(ngModel)]="filters.status"><option value="">Todos</option><option value="active">En seguimiento</option><option value="finished">Finalizado</option></select></label>
|
||||
@@ -40,7 +40,7 @@
|
||||
<label>Edad al M-CHAT <select name="age" [(ngModel)]="filters.age"><option value="">Todas</option><option value="16_23">16 a 23 meses</option><option value="24_29">24 a 29 meses</option><option value="30_36">30 a 36 meses</option></select></label>
|
||||
<label>M-CHAT mínimo <input type="number" name="mchatMin" [(ngModel)]="filters.mchatMin"></label><label>M-CHAT máximo <input type="number" name="mchatMax" [(ngModel)]="filters.mchatMax"></label>
|
||||
<label>CSS mínimo <input type="number" name="cssMin" [(ngModel)]="filters.cssMin"></label><label>CSS máximo <input type="number" name="cssMax" [(ngModel)]="filters.cssMax"></label>
|
||||
<label>EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
|
||||
<label>Estatus de EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
|
||||
@if (alterationsAvailable() && alterationTypes().length) { <label>Alteración <select name="alteration" [(ngModel)]="filters.alteration"><option value="">Todas</option>@for (item of alterationTypes(); track item.code) { <option [value]="item.code">{{ item.display }}</option> }</select></label> }
|
||||
<button type="submit">Aplicar filtros</button>
|
||||
</form>
|
||||
@@ -56,7 +56,7 @@
|
||||
}
|
||||
</section>
|
||||
@if (section() === 'seguimiento' && selected()) {
|
||||
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Seguimiento</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
|
||||
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Análisis de Riesgo</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
|
||||
@if (patientState() === 'cargando') { <p role="status">Consultando ficha…</p> }
|
||||
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
|
||||
@if (patientState() === 'listo') {
|
||||
|
||||
@@ -17,8 +17,17 @@ describe('TEA FHIR journey', () => {
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/fhir/Measure').flush(bundle(measure));
|
||||
http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] });
|
||||
return { c, http };
|
||||
return { c, http, fixture };
|
||||
}
|
||||
it('presenta las etiquetas de las tres secciones en la vista de estatus', () => {
|
||||
const { fixture, http } = setup();
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.tabs button'), tab => tab.textContent?.trim()))
|
||||
.toEqual(['Indicadores', 'Trazabilidad', 'Análisis de Riesgo']);
|
||||
expect(root.querySelector('section[aria-label="Consulta de indicadores"] h2')?.textContent).toBe('Indicadores');
|
||||
http.verify();
|
||||
});
|
||||
it('distinguishes zero, missing and masked values and requests the historical periods', () => {
|
||||
const { c, http } = setup();
|
||||
expect(c.value({ count: 0 }, 'count')).toBe('0');
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Covers `TeaEegApi`'s HTTP mapping: every method hits the contract's exact URL, verb, query and body,
|
||||
* and the multipart uploads send `reportProgress` so the UI can show progress. Fixtures: a real
|
||||
* `HttpClient` answered by `HttpTestingController`; each test flushes one canned response.
|
||||
*/
|
||||
import { HttpEvent, HttpEventType } from '@angular/common/http';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { TeaEegApi } from './tea-eeg.api';
|
||||
import { AnalyzeJob, ClusterStatus, TeaTrainBody } from './tea-eeg.types';
|
||||
|
||||
const STATUS: ClusterStatus = {
|
||||
mode: 'auto', scheduler: 'tcp://equipo:8786', reachable: true, workers: 4, expected_workers: 4,
|
||||
versions_ok: true, version_error: null, dashboard_ok: true, dashboard_url: 'http://equipo:8787/status',
|
||||
reference: { name: 'referencia_2026', edfs: 120 }, latency_ms: 42, error: null,
|
||||
};
|
||||
|
||||
// A finished analysis job, as `GET` answers it.
|
||||
const ANALYZE_JOB: AnalyzeJob = {
|
||||
id: 'a1', iniciado: '2026-11-01T10:00:00+00:00', estado: 'completado', codigo: 0,
|
||||
salida: '2 válidos, 1 no válido', error: '', cluster: null, ids: null,
|
||||
summary: { pending: 0, valid: 2, not_valid: 1, failed: 0 },
|
||||
};
|
||||
|
||||
describe('TeaEegApi', () => {
|
||||
let api: TeaEegApi;
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
api = TestBed.inject(TeaEegApi);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
// Fails if the health check changes route, or sends params when no cluster was picked.
|
||||
it('asks for the cluster health without params, and with them when a choice is given', () => {
|
||||
api.clusterStatus().subscribe((s) => expect(s).toEqual(STATUS));
|
||||
http.expectOne((r) => r.url === '/governance/tea/cluster' && r.params.keys().length === 0).flush(STATUS);
|
||||
|
||||
api.clusterStatus({ mode: 'remote', scheduler: 'tcp://equipo:8786' }).subscribe();
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/cluster');
|
||||
expect(req.request.params.get('mode')).toBe('remote');
|
||||
expect(req.request.params.get('scheduler')).toBe('tcp://equipo:8786');
|
||||
req.flush(STATUS);
|
||||
});
|
||||
|
||||
// Fails if the cohort list moves, or the file upload stops being multipart on the cohort's route.
|
||||
it('lists reference cohorts and uploads one cohort file with progress events', () => {
|
||||
api.listReferenceCohorts().subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/reference-cohorts').flush([]);
|
||||
|
||||
const types: HttpEventType[] = [];
|
||||
api.uploadReferenceFile('referencia_2026', new File(['x'], 'estudio.edf')).subscribe((e) => types.push(e.type));
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/reference-cohorts/referencia_2026/files');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.reportProgress).toBe(true);
|
||||
const body = req.request.body as FormData;
|
||||
expect(body.get('name')).toBeNull();
|
||||
expect((body.get('file') as File).name).toBe('estudio.edf');
|
||||
req.event({ type: HttpEventType.UploadProgress, loaded: 2, total: 4 });
|
||||
req.flush({ name: 'referencia_2026', file: 'estudio.edf', size_bytes: 4 });
|
||||
expect(types).toEqual([HttpEventType.Sent, HttpEventType.UploadProgress, HttpEventType.Response]);
|
||||
});
|
||||
|
||||
// Fails if training moves off the existing route, or the optional body stops being sent as-is.
|
||||
it('starts the TEA training on the existing train-jobs route', () => {
|
||||
api.startTeaTraining().subscribe();
|
||||
const empty = http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg/train-jobs');
|
||||
expect(empty.request.method).toBe('POST');
|
||||
expect(empty.request.body).toEqual({});
|
||||
empty.flush({ job: null });
|
||||
|
||||
const body: TeaTrainBody = {
|
||||
reference_name: 'referencia_2026', reference_dir: '/datos/tea/referencia_2026', reference_ages: 'edades.csv',
|
||||
line_hz: 50, promote: false, cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' },
|
||||
};
|
||||
api.startTeaTraining(body).subscribe();
|
||||
const req = http.expectOne((r) => r.url === '/governance/model-versions/tea/eeg/train-jobs');
|
||||
expect(req.request.body).toEqual(body);
|
||||
req.flush({ job: null });
|
||||
});
|
||||
|
||||
// Fails if the export URL loses its query or the import moves off the baselines route.
|
||||
it('builds the baselines export URL and imports a bundle with progress events', () => {
|
||||
expect(api.baselinesExportUrl()).toBe('/governance/tea/baselines/export?environment=prod');
|
||||
expect(api.baselinesExportUrl('staging', false)).toBe('/governance/tea/baselines/export?environment=staging&production=0');
|
||||
|
||||
const events: HttpEvent<{ sha256: string }>[] = [];
|
||||
api.importBaselines(new File(['zip'], 'baselines.zip')).subscribe((e) => events.push(e));
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/baselines/import');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.reportProgress).toBe(true);
|
||||
expect(((req.request.body as FormData).get('file') as File).name).toBe('baselines.zip');
|
||||
req.flush({ sha256: 'abc', imported: [] });
|
||||
expect(events.at(-1)?.type).toBe(HttpEventType.Response);
|
||||
});
|
||||
|
||||
// Fails if the analysis jobs change route, or the start/list/get verbs drift from the contract.
|
||||
it('starts, lists and gets analysis jobs on the analyze-jobs routes', () => {
|
||||
api.startAnalyzeJob({ all: true, cluster: { mode: 'sync' } }).subscribe((j) => expect(j).toEqual(ANALYZE_JOB));
|
||||
const started = http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs');
|
||||
expect(started.request.method).toBe('POST');
|
||||
expect(started.request.body).toEqual({ all: true, cluster: { mode: 'sync' } });
|
||||
started.flush(ANALYZE_JOB);
|
||||
|
||||
api.analyzeJobs().subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs').flush([ANALYZE_JOB]);
|
||||
|
||||
api.analyzeJob('a1').subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/analyze-jobs/a1').flush(ANALYZE_JOB);
|
||||
});
|
||||
|
||||
// Fails if the progress route stops being jobs/<kind>/<id>/progress for either kind.
|
||||
it('reads a run progress for training and analysis', () => {
|
||||
api.runProgress('train', 't1').subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/jobs/train/t1/progress').flush(null);
|
||||
|
||||
api.runProgress('analyze', 'a1').subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/jobs/analyze/a1/progress').flush(null);
|
||||
});
|
||||
|
||||
// Fails if the baseline check routes drift, or the curve loses its metric query.
|
||||
it('reads baseline metric names and one metric curve', () => {
|
||||
api.baselineMetrics('tea_nsr', 3).subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/baselines/tea_nsr/3/metrics').flush(['alpha_peak']);
|
||||
|
||||
api.baselineCurve('tea_nsr', 3, 'alpha_peak').subscribe();
|
||||
const req = http.expectOne((r) => r.url === '/governance/tea/baselines/tea_nsr/3/curve');
|
||||
expect(req.request.params.get('metric')).toBe('alpha_peak');
|
||||
req.flush(null);
|
||||
});
|
||||
|
||||
// Fails if the EEG catalog loses its paging, or the metrics/summary routes move.
|
||||
it('lists EEGs paged and reads one EEG metrics and the summary', () => {
|
||||
api.eegList().subscribe();
|
||||
const list = http.expectOne((r) => r.url === '/governance/tea/eeg');
|
||||
expect(list.request.params.get('limit')).toBe('200');
|
||||
expect(list.request.params.get('offset')).toBe('0');
|
||||
list.flush([]);
|
||||
|
||||
api.eegList(50, 100).subscribe();
|
||||
const paged = http.expectOne((r) => r.url === '/governance/tea/eeg');
|
||||
expect(paged.request.params.get('limit')).toBe('50');
|
||||
expect(paged.request.params.get('offset')).toBe('100');
|
||||
paged.flush([]);
|
||||
|
||||
api.eegMetrics(7).subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/7/metrics').flush(null);
|
||||
|
||||
api.eegSummary().subscribe();
|
||||
http.expectOne((r) => r.url === '/governance/tea/eeg/summary').flush(null);
|
||||
});
|
||||
|
||||
// Fails if the EEG upload stops sending the file under the `file` field, or drops the patient id.
|
||||
it('uploads one EDF with an optional patient id', () => {
|
||||
api.uploadEeg(new File(['x'], 'estudio.edf')).subscribe();
|
||||
const bare = http.expectOne((r) => r.url === '/governance/tea/eeg/upload');
|
||||
expect(bare.request.method).toBe('POST');
|
||||
const form = bare.request.body as FormData;
|
||||
expect((form.get('file') as File).name).toBe('estudio.edf');
|
||||
expect(form.get('patient_id')).toBeNull();
|
||||
bare.flush({ eeg_id: 7, lab_id: null, created: true });
|
||||
|
||||
api.uploadEeg(new File(['x'], 'otro.edf'), 42).subscribe();
|
||||
const withPatient = http.expectOne((r) => r.url === '/governance/tea/eeg/upload');
|
||||
expect((withPatient.request.body as FormData).get('patient_id')).toBe('42');
|
||||
withPatient.flush({ eeg_id: 8, lab_id: 'L-2', created: false });
|
||||
});
|
||||
|
||||
// Fails if the recalculation moves off the existing indicators route, or sends a body without a cluster.
|
||||
it('recalculates the TEA indicators with an optional cluster body', () => {
|
||||
api.recalculateTeaIndicators().subscribe();
|
||||
const bare = http.expectOne((r) => r.url === '/reportes/indicadores/tea/recalcular');
|
||||
expect(bare.request.method).toBe('POST');
|
||||
expect(bare.request.body).toEqual({});
|
||||
bare.flush({ pendiente: true });
|
||||
|
||||
api.recalculateTeaIndicators({ mode: 'local' }).subscribe();
|
||||
const withCluster = http.expectOne((r) => r.url === '/reportes/indicadores/tea/recalcular');
|
||||
expect(withCluster.request.body).toEqual({ cluster: { mode: 'local' } });
|
||||
withCluster.flush({ pendiente: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { HttpClient, HttpEvent, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import {
|
||||
AnalyzeBody,
|
||||
AnalyzeJob,
|
||||
BaselineCurve,
|
||||
BaselineImport,
|
||||
ClusterChoice,
|
||||
ClusterStatus,
|
||||
EegId,
|
||||
EegListItem,
|
||||
EegMetrics,
|
||||
EegPreview,
|
||||
EegSummary,
|
||||
EegUploadResult,
|
||||
ReferenceCohort,
|
||||
ReferenceFileUpload,
|
||||
RunProgress,
|
||||
TeaTrainBody,
|
||||
TeaTrainJob,
|
||||
} from './tea-eeg.types';
|
||||
|
||||
/** `/governance/tea/*`: the TEA·EEG cluster, reference cohorts, training, baseline bundles, analysis
|
||||
* jobs and the EEG catalog. The multipart uploads report progress events. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class TeaEegApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** Effective cluster health after resolving 'auto'; both query params optional. */
|
||||
clusterStatus(choice?: ClusterChoice): Observable<ClusterStatus> {
|
||||
const params = toParams(choice ? { mode: choice.mode, scheduler: choice.scheduler } : {});
|
||||
return this.http.get<ClusterStatus>('/governance/tea/cluster', { params });
|
||||
}
|
||||
|
||||
listReferenceCohorts(): Observable<ReferenceCohort[]> {
|
||||
return this.http.get<ReferenceCohort[]>('/governance/tea/reference-cohorts');
|
||||
}
|
||||
|
||||
/** One `.edf` or the cohort's `edades.csv`; emits upload progress events, then the stored file. */
|
||||
uploadReferenceFile(name: string, file: File): Observable<HttpEvent<ReferenceFileUpload>> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return this.http.post<ReferenceFileUpload>(`/governance/tea/reference-cohorts/${encodeURIComponent(name)}/files`, form, {
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
});
|
||||
}
|
||||
|
||||
/** Starts the TEA training in the background: 202 with the job, 409 with the running one; the body
|
||||
* overrides the server's `TEA_REFERENCE_*` settings. */
|
||||
startTeaTraining(body: TeaTrainBody = {}): Observable<{ job: TeaTrainJob }> {
|
||||
return this.http.post<{ job: TeaTrainJob }>('/governance/model-versions/tea/eeg/train-jobs', body);
|
||||
}
|
||||
|
||||
/** Where the zip bundle of promoted baselines downloads from; `production=0` excludes them. */
|
||||
baselinesExportUrl(environment = 'prod', production?: boolean): string {
|
||||
let query = `environment=${encodeURIComponent(environment)}`;
|
||||
if (production !== undefined) query += `&production=${production ? 1 : 0}`;
|
||||
return `/governance/tea/baselines/export?${query}`;
|
||||
}
|
||||
|
||||
/** Imports a baseline bundle; emits upload progress events, then what was imported. */
|
||||
importBaselines(file: File): Observable<HttpEvent<BaselineImport>> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return this.http.post<BaselineImport>('/governance/tea/baselines/import', form, {
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
});
|
||||
}
|
||||
|
||||
/** Starts an EEG analysis: 202 with the job, 409 while one runs. */
|
||||
startAnalyzeJob(body: AnalyzeBody): Observable<AnalyzeJob> {
|
||||
return this.http.post<AnalyzeJob>('/governance/tea/eeg/analyze-jobs', body);
|
||||
}
|
||||
|
||||
/** The analysis jobs, newest first. */
|
||||
analyzeJobs(): Observable<AnalyzeJob[]> {
|
||||
return this.http.get<AnalyzeJob[]>('/governance/tea/eeg/analyze-jobs');
|
||||
}
|
||||
|
||||
analyzeJob(id: string): Observable<AnalyzeJob> {
|
||||
return this.http.get<AnalyzeJob>(`/governance/tea/eeg/analyze-jobs/${encodeURIComponent(id)}`);
|
||||
}
|
||||
|
||||
/** Live progress of a training (`kind: 'train'`) or analysis (`'analyze'`) run; 404 before the first
|
||||
* sample. Non-Dask jobs answer `cluster: null` and `tasks: null`. */
|
||||
runProgress(kind: 'train' | 'analyze', jobId: string): Observable<RunProgress> {
|
||||
return this.http.get<RunProgress>(`/governance/tea/jobs/${kind}/${encodeURIComponent(jobId)}/progress`);
|
||||
}
|
||||
|
||||
/** The metric names a baseline version has a curve for. */
|
||||
baselineMetrics(scenario: string, version: number): Observable<string[]> {
|
||||
return this.http.get<string[]>(`/governance/tea/baselines/${encodeURIComponent(scenario)}/${version}/metrics`);
|
||||
}
|
||||
|
||||
/** One metric's curve across age for a baseline version. */
|
||||
baselineCurve(scenario: string, version: number, metric: string): Observable<BaselineCurve> {
|
||||
return this.http.get<BaselineCurve>(`/governance/tea/baselines/${encodeURIComponent(scenario)}/${version}/curve`, {
|
||||
params: new HttpParams().set('metric', metric),
|
||||
});
|
||||
}
|
||||
|
||||
/** The EEG catalog, paged; feeds the ticked list of the analysis step. */
|
||||
eegList(limit = 200, offset = 0): Observable<EegListItem[]> {
|
||||
return this.http.get<EegListItem[]>('/governance/tea/eeg', { params: toParams({ limit, offset }) });
|
||||
}
|
||||
|
||||
eegMetrics(eegId: EegId): Observable<EegMetrics> {
|
||||
return this.http.get<EegMetrics>(`/governance/tea/eeg/${encodeURIComponent(eegId)}/metrics`);
|
||||
}
|
||||
|
||||
eegSummary(): Observable<EegSummary> {
|
||||
return this.http.get<EegSummary>('/governance/tea/eeg/summary');
|
||||
}
|
||||
|
||||
/** One `.edf` through the existing import pipeline; 400 when MNE cannot open it. */
|
||||
uploadEeg(file: File, patientId?: number): Observable<EegUploadResult> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (patientId !== undefined) form.append('patient_id', String(patientId));
|
||||
return this.http.post<EegUploadResult>('/governance/tea/eeg/upload', form);
|
||||
}
|
||||
|
||||
/** Analyses one `.edf` (and its ADOS-2 `.pdf`, if any) in memory; nothing is written to a database. */
|
||||
previewEeg(edf: File, ados2?: File): Observable<EegPreview> {
|
||||
const form = new FormData();
|
||||
form.append('edf', edf);
|
||||
if (ados2) form.append('ados2', ados2);
|
||||
return this.http.post<EegPreview>('/governance/tea/eeg/preview', form);
|
||||
}
|
||||
|
||||
/** Recomputes the TEA indicators on the given cluster; the body is optional. */
|
||||
recalculateTeaIndicators(cluster?: ClusterChoice): Observable<{ pendiente: boolean }> {
|
||||
return this.http.post<{ pendiente: boolean }>('/reportes/indicadores/tea/recalcular', cluster ? { cluster } : {});
|
||||
}
|
||||
}
|
||||
|
||||
function toParams(filters: Record<string, string | number | boolean | undefined>): HttpParams {
|
||||
let params = new HttpParams();
|
||||
for (const [key, value] of Object.entries(filters)) {
|
||||
if (value !== undefined && value !== null && value !== '') params = params.set(key, String(value));
|
||||
}
|
||||
return params;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/** Shapes of the `/governance/tea/*` JSON contract: cluster health, reference cohorts, TEA training,
|
||||
* baseline bundles, EEG analysis jobs and the EEG catalog. */
|
||||
import { TrainingJob } from './governance.types';
|
||||
|
||||
export type ClusterMode = 'auto' | 'local' | 'remote' | 'sync';
|
||||
|
||||
/** Where the work runs; `scheduler` is only meaningful for 'remote'. */
|
||||
export interface ClusterChoice {
|
||||
mode: ClusterMode;
|
||||
scheduler?: string;
|
||||
}
|
||||
|
||||
export type JobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido';
|
||||
|
||||
/** Effective cluster health after resolving 'auto'. */
|
||||
export interface ClusterStatus {
|
||||
mode: ClusterMode;
|
||||
scheduler: string | null;
|
||||
reachable: boolean;
|
||||
workers: number | null;
|
||||
expected_workers: number | null;
|
||||
versions_ok: boolean | null;
|
||||
version_error: string | null;
|
||||
dashboard_ok: boolean | null;
|
||||
dashboard_url: string | null;
|
||||
reference: { name: string; edfs: number } | null;
|
||||
latency_ms: number | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/** One reference cohort folder under `TEA_REFERENCE_ROOT`. */
|
||||
export interface ReferenceCohort {
|
||||
name: string;
|
||||
edfs: number;
|
||||
size_bytes: number;
|
||||
has_ages: boolean;
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** The answer to uploading one cohort file (`.edf` or `edades.csv`): 201. */
|
||||
export interface ReferenceFileUpload {
|
||||
name: string;
|
||||
file: string;
|
||||
size_bytes: number;
|
||||
}
|
||||
|
||||
/** Body of the TEA training route; fields override the server's `TEA_REFERENCE_*`. */
|
||||
export interface TeaTrainBody {
|
||||
reference_name?: string;
|
||||
reference_dir?: string;
|
||||
reference_ages?: string;
|
||||
line_hz?: number;
|
||||
promote?: boolean;
|
||||
cluster?: ClusterChoice;
|
||||
}
|
||||
|
||||
/** The training job the existing route answers, with the cluster it ran on. */
|
||||
export interface TeaTrainJob extends TrainingJob {
|
||||
cluster: ClusterChoice | null;
|
||||
}
|
||||
|
||||
/** The answer to importing a baseline bundle. */
|
||||
export interface BaselineImport {
|
||||
sha256: string;
|
||||
imported: { scenario: string; version: number }[];
|
||||
}
|
||||
|
||||
/** Body of an analysis job start. */
|
||||
export interface AnalyzeBody {
|
||||
all?: boolean;
|
||||
limit?: number;
|
||||
ids?: (number | string)[];
|
||||
cluster?: ClusterChoice;
|
||||
}
|
||||
|
||||
/** Counts behind an analysis job, present once it finished. */
|
||||
export interface AnalyzeSummary {
|
||||
pending: number;
|
||||
valid: number;
|
||||
not_valid: number;
|
||||
failed: number;
|
||||
}
|
||||
|
||||
/** An EEG analysis job in the background. */
|
||||
export interface AnalyzeJob {
|
||||
id: string;
|
||||
iniciado: string;
|
||||
estado: JobState;
|
||||
codigo: number | null;
|
||||
salida: string;
|
||||
error: string;
|
||||
cluster: ClusterChoice | null;
|
||||
ids: (number | string)[] | null;
|
||||
summary: AnalyzeSummary | null;
|
||||
}
|
||||
|
||||
/** Live progress of a training or analysis run. */
|
||||
export interface RunProgress {
|
||||
updated_at: string;
|
||||
phase: string;
|
||||
done: number;
|
||||
total: number;
|
||||
elapsed_s: number;
|
||||
eta_s: number | null;
|
||||
tasks: { processing: number; waiting: number; memory: number; erred: number } | null;
|
||||
cluster: {
|
||||
mode: ClusterMode;
|
||||
scheduler: string | null;
|
||||
workers: WorkerSample[];
|
||||
cpu_pct: number;
|
||||
memory_pct: number;
|
||||
} | null;
|
||||
history: { t: number; done: number; cpu_pct: number; memory_pct: number }[];
|
||||
}
|
||||
|
||||
/** One Dask worker sample inside a run's progress. */
|
||||
export interface WorkerSample {
|
||||
name: string;
|
||||
cpu_pct: number;
|
||||
memory_bytes: number;
|
||||
memory_limit: number | null;
|
||||
executing: number;
|
||||
threads: number;
|
||||
}
|
||||
|
||||
/** A stored baseline curve for one metric. */
|
||||
export interface BaselineCurve {
|
||||
scenario: string;
|
||||
version: number;
|
||||
metric: string;
|
||||
edad_meses: number[];
|
||||
p5: number[];
|
||||
p25: number[];
|
||||
mediana: number[];
|
||||
p75: number[];
|
||||
p95: number[];
|
||||
}
|
||||
|
||||
/** One EEG's metric values with their z scores against the baseline. */
|
||||
export interface EegMetrics {
|
||||
eeg_id: EegId;
|
||||
valid: boolean | null;
|
||||
level: string | null;
|
||||
age_months: number | null;
|
||||
metrics: { name: string; value: number; z: number | null; outside: -1 | 0 | 1 | null; model: string | null }[];
|
||||
}
|
||||
|
||||
export type EegId = number | string;
|
||||
|
||||
/** One EEG of the catalog, as listed for the analysis step's ticked list. */
|
||||
export interface EegListItem {
|
||||
id: EegId;
|
||||
lab_id: string | null;
|
||||
patient_id: number | null;
|
||||
study_date: string | null;
|
||||
valid: boolean | null;
|
||||
analysed: boolean;
|
||||
}
|
||||
|
||||
/** The answer to uploading one `.edf`: 201. */
|
||||
export interface EegUploadResult {
|
||||
eeg_id: EegId | null;
|
||||
lab_id: string | null;
|
||||
created: boolean;
|
||||
}
|
||||
|
||||
/** Catalog counts for the result step. */
|
||||
export interface EegSummary {
|
||||
eegs: number;
|
||||
analysed: number;
|
||||
valid: number;
|
||||
not_valid: number;
|
||||
failed: number;
|
||||
metrics: number;
|
||||
metrics_with_z: number;
|
||||
high: number;
|
||||
low: number;
|
||||
fhir_eegs: number;
|
||||
fhir_metrics: number;
|
||||
}
|
||||
|
||||
/** The analysis of one EDF (and its ADOS-2 report) that the server did without storing anything:
|
||||
* a `$resumen-tea`-shaped FHIR bundle and the notices about what could not be read. */
|
||||
export interface EegPreview {
|
||||
bundle: unknown;
|
||||
avisos: string[];
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<h3>Alcance del análisis</h3>
|
||||
<mat-radio-group aria-label="Alcance del análisis" [ngModel]="scope()" (ngModelChange)="scope.set($event)" [disabled]="busy()">
|
||||
<mat-radio-button value="pending">Pendientes</mat-radio-button>
|
||||
<mat-radio-button value="limit">Primeros N</mat-radio-button>
|
||||
<mat-radio-button value="selected">EEGs elegidos</mat-radio-button>
|
||||
</mat-radio-group>
|
||||
@if (scope() === 'limit') {
|
||||
<div class="controls"><label>Cantidad <input type="number" min="1" step="1" [ngModel]="limit()" (ngModelChange)="limit.set($event)" [disabled]="busy()" /></label></div>
|
||||
}
|
||||
@if (scope() === 'selected') {
|
||||
<app-eeg-picker [(selected)]="selected" [revision]="revision()" [disabled]="busy()" />
|
||||
}
|
||||
<div class="controls">
|
||||
<button mat-flat-button type="button" [disabled]="!canAnalyze()" (click)="analyze()">{{ starting() ? 'Iniciando…' : 'Analizar' }}</button>
|
||||
<button mat-stroked-button type="button" [disabled]="busy()" (click)="recalculate()">{{ recalculating() ? 'Solicitando…' : 'Ejecutar ciclo de indicadores' }}</button>
|
||||
</div>
|
||||
@if (actionError()) { <p role="alert">{{ actionError() }}</p> }
|
||||
@if (cycleMessage()) { <p role="status">{{ cycleMessage() }}</p> }
|
||||
@if (loading()) { <p role="status">Cargando análisis…</p> }
|
||||
@if (jobError()) {
|
||||
<p role="alert">{{ jobError() }}</p>
|
||||
<button mat-button type="button" [disabled]="loading()" (click)="refreshJobs()">Volver a consultar</button>
|
||||
} @else if (!loading() && !job()) { <p>Todavía no hay análisis de EEG.</p> }
|
||||
|
||||
@if (job(); as current) {
|
||||
<h3>Último análisis · {{ states[current.estado] }}</h3>
|
||||
<app-run-monitor kind="analyze" [jobId]="current.id" [running]="current.estado === 'en_curso'" />
|
||||
@if (current.summary; as summary) {
|
||||
<dl>
|
||||
<div><dt>Pendientes</dt><dd>{{ summary.pending }}</dd></div>
|
||||
<div><dt>Válidos</dt><dd>{{ summary.valid }}</dd></div>
|
||||
<div><dt>No válidos</dt><dd>{{ summary.not_valid }}</dd></div>
|
||||
<div><dt>Fallidos</dt><dd>{{ summary.failed }}</dd></div>
|
||||
</dl>
|
||||
}
|
||||
@if (current.error) { <p role="alert">{{ current.error }}</p> }
|
||||
@if (current.salida) {
|
||||
<details><summary>Ver últimas líneas de salida</summary><pre>{{ current.salida }}</pre></details>
|
||||
}
|
||||
}
|
||||
|
||||
<details class="upload">
|
||||
<summary>Subir EDF</summary>
|
||||
<div class="controls">
|
||||
<label>Archivo EDF <input #edf type="file" accept=".edf" [disabled]="uploading()" (change)="chooseFile($event)" /></label>
|
||||
@if (!storeless()) {
|
||||
<label>ID del paciente (opcional) <input type="number" min="0" step="1" [ngModel]="patientId()" (ngModelChange)="patientId.set($event)" [disabled]="uploading()" /></label>
|
||||
}
|
||||
@if (file()) {
|
||||
<label>Informe ADOS-2 (PDF, opcional) <input type="file" accept=".pdf" [disabled]="uploading()" (change)="chooseAdos2($event)" /></label>
|
||||
<mat-checkbox [checked]="storeless()" [disabled]="uploading() || ados2File() !== null" (change)="viewOnly.set($event.checked)">Solo ver resultados, sin guardar en la base de datos</mat-checkbox>
|
||||
}
|
||||
@if (storeless()) {
|
||||
<button mat-flat-button type="button" [disabled]="!canPreview()" (click)="preview()">{{ uploading() ? 'Analizando…' : 'Ver resultados' }}</button>
|
||||
} @else {
|
||||
<button mat-stroked-button type="button" [disabled]="!canUpload()" (click)="upload(edf)">{{ uploading() ? 'Subiendo…' : 'Subir EDF' }}</button>
|
||||
}
|
||||
</div>
|
||||
@if (uploadError()) { <p role="alert">{{ uploadError() }}</p> }
|
||||
@if (uploaded(); as result) {
|
||||
<p role="status">EEG {{ result.eeg_id ?? '—' }} · Laboratorio {{ result.lab_id ?? '—' }} · {{ result.created ? 'Creado' : 'Actualizado' }}</p>
|
||||
}
|
||||
</details>
|
||||
@@ -0,0 +1,4 @@
|
||||
dl { display: flex; flex-wrap: wrap; gap: 1rem; }
|
||||
dd { margin: 0; font-weight: 600; }
|
||||
pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 16rem; overflow: auto; }
|
||||
.upload { border-top: 1px solid var(--mat-sys-outline-variant); margin-block-start: 1rem; padding-block: .75rem; }
|
||||
@@ -0,0 +1,194 @@
|
||||
/** Pins analysis, conflict recovery and EDF uploads against mocked HTTP jobs and catalog rows. */
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { of } from 'rxjs';
|
||||
import { TeaPacienteDetalle, TeaSeguimientoService } from '../../../features/indicadores/tea-seguimiento.service';
|
||||
import { AnalyzeJob } from '../../api/tea-eeg.types';
|
||||
import { AnalyzeStepComponent } from './analyze-step';
|
||||
|
||||
const jobs = '/governance/tea/eeg/analyze-jobs';
|
||||
const progress = '/governance/tea/jobs/analyze/a1/progress';
|
||||
const upload = '/governance/tea/eeg/upload';
|
||||
const preview = '/governance/tea/eeg/preview';
|
||||
|
||||
// A running job discovered on conflict or returned by a successful start.
|
||||
const running: AnalyzeJob = {
|
||||
id: 'a1', iniciado: '2026-11-23T00:00:00Z', estado: 'en_curso', codigo: null,
|
||||
salida: '', error: '', cluster: null, ids: null, summary: null,
|
||||
};
|
||||
|
||||
describe('AnalyzeStepComponent', () => {
|
||||
let http: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
/** Creates the step with a remote choice and an empty analysis history. */
|
||||
function create() {
|
||||
const fixture = TestBed.createComponent(AnalyzeStepComponent);
|
||||
fixture.componentRef.setInput('choice', { mode: 'remote', scheduler: 'tcp://equipo:8786' });
|
||||
fixture.detectChanges();
|
||||
http.expectOne(jobs).flush([]);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
/** Fails if the limit or cluster is omitted, polling stops early, or final results are hidden. */
|
||||
it('starts a bounded run and displays its final summary and tail', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.scope.set('limit');
|
||||
step.limit.set(5);
|
||||
step.analyze();
|
||||
const request = http.expectOne(jobs);
|
||||
expect(request.request.body).toEqual({ limit: 5, cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } });
|
||||
request.flush(running);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
vi.advanceTimersByTime(2000);
|
||||
const runningProgress = http.expectOne(progress);
|
||||
http.expectOne(`${jobs}/a1`).flush({
|
||||
...running, estado: 'completado', codigo: 0, salida: 'EEG 14 procesado',
|
||||
summary: { pending: 1, valid: 2, not_valid: 1, failed: 1 },
|
||||
});
|
||||
fixture.detectChanges();
|
||||
expect(runningProgress.cancelled).toBe(true);
|
||||
http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
expect(fixture.nativeElement.textContent).toContain('EEG 14 procesado');
|
||||
expect(fixture.nativeElement.querySelector('dd').textContent).toBe('1');
|
||||
vi.advanceTimersByTime(2000);
|
||||
http.expectNone(`${jobs}/a1`);
|
||||
fixture.destroy();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
/** Fails if pending scope requests a full rerun, a conflict hides the active job, or an unknown EEG is silent. */
|
||||
it('recovers the active job on conflict and explains unknown EEGs', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
step.analyze();
|
||||
const missing = http.expectOne(jobs);
|
||||
expect(missing.request.body).toEqual({ cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } });
|
||||
missing.flush(null, { status: 404, statusText: 'Not Found' });
|
||||
expect(step.actionError()).toContain('No se encontró');
|
||||
|
||||
step.analyze();
|
||||
http.expectOne(jobs).flush(null, { status: 409, statusText: 'Conflict' });
|
||||
http.expectOne(jobs).flush([running]);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(progress).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
expect(fixture.nativeElement.textContent).toContain('Ya hay un análisis de EEG en curso.');
|
||||
expect(step.canAnalyze()).toBe(false);
|
||||
});
|
||||
|
||||
/** Fails if an invalid EDF gets selected, or a successful upload fails to tick its catalog row. */
|
||||
it('keeps a failed EDF retryable and ticks the successfully uploaded EEG', async () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const input: HTMLInputElement = fixture.nativeElement.querySelector('input[type=file]');
|
||||
step.file.set(new File(['edf'], 'estudio.edf'));
|
||||
step.patientId.set(42);
|
||||
step.upload(input);
|
||||
const failed = http.expectOne(upload);
|
||||
expect(failed.request.body.get('patient_id')).toBe('42');
|
||||
failed.flush({ error: 'EDF inválido' }, { status: 400, statusText: 'Bad Request' });
|
||||
expect(step.uploadError()).toBe('EDF inválido');
|
||||
expect(step.selected()).toEqual([]);
|
||||
expect(step.canUpload()).toBe(true);
|
||||
|
||||
step.upload(input);
|
||||
http.expectOne(upload).flush({ eeg_id: '8', lab_id: 'LAB-8', created: true });
|
||||
fixture.detectChanges();
|
||||
http.expectOne((req) => req.url === '/governance/tea/eeg').flush([
|
||||
{ id: 8, lab_id: 'LAB-8', patient_id: 42, study_date: null, valid: null, analysed: false },
|
||||
]);
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('input[type=checkbox]').checked).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Creado');
|
||||
});
|
||||
|
||||
/** Fails if the analysis by selection stops sending UUID ids, which real EEGs carry, as text. */
|
||||
it('analyses chosen EEGs by their UUID ids', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const uuid = 'ed257fbd-61d5-4c9c-bb72-00c4ec550961';
|
||||
step.scope.set('selected');
|
||||
step.selected.set([uuid]);
|
||||
expect(step.canAnalyze()).toBe(true);
|
||||
step.analyze();
|
||||
const request = http.expectOne('/governance/tea/eeg/analyze-jobs');
|
||||
expect(request.request.body.ids).toEqual([uuid]);
|
||||
request.flush({ id: 'j1', estado: 'en_curso', ids: [uuid], cluster: null, summary: null, salida: '', error: '', codigo: null, iniciado: '' });
|
||||
});
|
||||
|
||||
/** Fails if the TEA indicator cycle loses the selected cluster. */
|
||||
it('requests the indicator cycle on the selected cluster', () => {
|
||||
const fixture = create();
|
||||
fixture.componentInstance.recalculate();
|
||||
const request = http.expectOne('/reportes/indicadores/tea/recalcular');
|
||||
expect(request.request.body).toEqual({ cluster: { mode: 'remote', scheduler: 'tcp://equipo:8786' } });
|
||||
request.flush({ pendiente: true });
|
||||
expect(fixture.componentInstance.cycleMessage()).toContain('Pendiente');
|
||||
});
|
||||
|
||||
const edf = () => new File(['x'], 'estudio.edf');
|
||||
const choose = (step: AnalyzeStepComponent, file: File | null, ados2: File | null = null) => {
|
||||
step.chooseFile({ target: { files: { item: () => file } } } as unknown as Event);
|
||||
if (ados2) step.chooseAdos2({ target: { files: { item: () => ados2 } } } as unknown as Event);
|
||||
};
|
||||
|
||||
/** Fails if choosing an ADOS-2 report still offers a stored upload, or if the report is sent with the wrong field. */
|
||||
it('sends an EDF and its ADOS-2 report only to the preview and opens the record', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
const detalle = { id_seudonimo: 'vista-previa' };
|
||||
vi.spyOn(TestBed.inject(TeaSeguimientoService), 'vistaPrevia').mockReturnValue(of(detalle as unknown as TeaPacienteDetalle));
|
||||
const open = vi.spyOn(TestBed.inject(MatDialog), 'open').mockReturnValue(undefined as never);
|
||||
choose(step, edf(), new File(['p'], 'ados2.pdf'));
|
||||
expect(step.storeless()).toBe(true);
|
||||
step.preview();
|
||||
const request = http.expectOne(preview);
|
||||
expect((request.request.body as FormData).get('edf')).toBeInstanceOf(File);
|
||||
expect(((request.request.body as FormData).get('ados2') as File).name).toBe('ados2.pdf');
|
||||
request.flush({ bundle: { resourceType: 'Bundle' }, avisos: ['aviso'] });
|
||||
expect(open.mock.calls[0][1]?.data).toEqual({ detalle, avisos: ['aviso'], archivo: 'estudio.edf' });
|
||||
http.expectNone(upload);
|
||||
expect(step.uploaded()).toBeNull();
|
||||
});
|
||||
|
||||
/** Fails if the stored upload stops being the default for a lone EDF, or the view-only box does not switch the button. */
|
||||
it('keeps the stored upload unless the EDF is for viewing only', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
choose(step, edf());
|
||||
expect(step.storeless()).toBe(false);
|
||||
step.viewOnly.set(true);
|
||||
expect(step.storeless()).toBe(true);
|
||||
expect(step.canPreview()).toBe(true);
|
||||
choose(step, null);
|
||||
expect(step.viewOnly()).toBe(false);
|
||||
});
|
||||
|
||||
/** Fails if a non-PDF report can be sent, or a server refusal is not shown. */
|
||||
it('rejects a report that is not a PDF and shows the preview error', () => {
|
||||
const fixture = create();
|
||||
const step = fixture.componentInstance;
|
||||
choose(step, edf(), new File(['p'], 'ados2.txt'));
|
||||
expect(step.canPreview()).toBe(false);
|
||||
expect(step.uploadError()).toBe('Elige el informe ADOS-2 en PDF.');
|
||||
choose(step, edf(), new File(['p'], 'ados2.pdf'));
|
||||
step.preview();
|
||||
http.expectOne(preview).flush({ error: 'EDF ilegible' }, { status: 400, statusText: 'Bad Request' });
|
||||
expect(step.uploadError()).toBe('EDF ilegible');
|
||||
expect(step.uploading()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import { Component, DestroyRef, OnInit, computed, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatRadioModule } from '@angular/material/radio';
|
||||
import { finalize, exhaustMap, catchError, EMPTY, map, switchMap, timer } from 'rxjs';
|
||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { AnalyzeBody, AnalyzeJob, ClusterChoice, EegId, EegUploadResult, JobState } from '../../api/tea-eeg.types';
|
||||
import { TeaSeguimientoService } from '../../../features/indicadores/tea-seguimiento.service';
|
||||
import { EegPicker } from '../eeg-picker/eeg-picker';
|
||||
import { EegPreviewData, EegPreviewDialog } from '../eeg-preview-dialog/eeg-preview-dialog';
|
||||
import { RunMonitorComponent } from '../run-monitor/run-monitor';
|
||||
|
||||
@Component({
|
||||
selector: 'app-analyze-step',
|
||||
imports: [EegPicker, FormsModule, MatButtonModule, MatCheckboxModule, MatRadioModule, RunMonitorComponent],
|
||||
templateUrl: './analyze-step.html',
|
||||
styleUrls: ['../eeg-step.scss', './analyze-step.scss'],
|
||||
})
|
||||
export class AnalyzeStepComponent implements OnInit {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly tea = inject(TeaSeguimientoService);
|
||||
readonly choice = input<ClusterChoice>({ mode: 'auto' });
|
||||
readonly scope = signal<'pending' | 'limit' | 'selected'>('pending');
|
||||
readonly limit = signal<number | null>(10);
|
||||
readonly selected = signal<EegId[]>([]);
|
||||
readonly revision = signal(0);
|
||||
readonly jobs = signal<AnalyzeJob[]>([]);
|
||||
readonly job = computed(() => this.jobs().find((job) => job.estado === 'en_curso') ?? this.jobs()[0]);
|
||||
private readonly runningId = computed(() => this.job()?.estado === 'en_curso' ? this.job()?.id : undefined);
|
||||
readonly loading = signal(false);
|
||||
readonly starting = signal(false);
|
||||
readonly recalculating = signal(false);
|
||||
readonly jobError = signal('');
|
||||
readonly actionError = signal('');
|
||||
readonly cycleMessage = signal('');
|
||||
readonly busy = computed(() => this.loading() || this.starting() || this.recalculating() || !!this.runningId());
|
||||
readonly canAnalyze = computed(() => !this.busy() && (
|
||||
this.scope() === 'pending' ||
|
||||
(this.scope() === 'selected' ? this.selected().length > 0 : positiveInteger(this.limit()))
|
||||
));
|
||||
readonly file = signal<File | null>(null);
|
||||
readonly patientId = signal<number | null>(null);
|
||||
readonly uploading = signal(false);
|
||||
readonly uploadError = signal('');
|
||||
readonly uploaded = signal<EegUploadResult | null>(null);
|
||||
readonly canUpload = computed(() => !this.uploading() && /\.edf$/i.test(this.file()?.name ?? '') &&
|
||||
(this.patientId() === null || (Number.isSafeInteger(this.patientId()) && this.patientId()! >= 0)));
|
||||
readonly ados2File = signal<File | null>(null);
|
||||
readonly viewOnly = signal(false);
|
||||
/** An ADOS-2 report is never stored (there is no patient to attach it to), so it always means a view-only analysis. */
|
||||
readonly storeless = computed(() => this.viewOnly() || this.ados2File() !== null);
|
||||
readonly canPreview = computed(() => !this.uploading() && /\.edf$/i.test(this.file()?.name ?? '') &&
|
||||
(this.ados2File() === null || /\.pdf$/i.test(this.ados2File()!.name)));
|
||||
readonly states: Record<JobState, string> = {
|
||||
en_curso: 'En curso', completado: 'Completado', entrenado_sin_promover: 'Completado',
|
||||
fallido: 'Falló', interrumpido: 'Interrumpido',
|
||||
};
|
||||
|
||||
constructor() {
|
||||
effect((cleanup) => {
|
||||
const id = this.runningId();
|
||||
if (!id) return;
|
||||
const polling = timer(2000, 2000).pipe(exhaustMap(() => this.api.analyzeJob(id).pipe(
|
||||
catchError((error) => {
|
||||
this.jobError.set(apiErrorMessage(error, error.status === 404
|
||||
? 'No se encontró el trabajo de análisis.' : 'No se pudo consultar el trabajo de análisis.'));
|
||||
if (error.status === 404) this.jobs.update((jobs) => jobs.filter((job) => job.id !== id));
|
||||
return EMPTY;
|
||||
}),
|
||||
))).subscribe((job) => {
|
||||
this.jobError.set('');
|
||||
this.storeJob(job);
|
||||
if (job.estado !== 'en_curso') this.revision.update((value) => value + 1);
|
||||
});
|
||||
cleanup(() => polling.unsubscribe());
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.refreshJobs();
|
||||
}
|
||||
|
||||
refreshJobs(): void {
|
||||
if (this.loading()) return;
|
||||
this.loading.set(true);
|
||||
this.jobError.set('');
|
||||
this.api.analyzeJobs().pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.loading.set(false)),
|
||||
).subscribe({
|
||||
next: (jobs) => this.jobs.set(jobs),
|
||||
error: (error) => this.jobError.set(apiErrorMessage(error, 'No se pudieron cargar los análisis.')),
|
||||
});
|
||||
}
|
||||
|
||||
analyze(): void {
|
||||
if (!this.canAnalyze()) return;
|
||||
const body: AnalyzeBody = { cluster: this.choice() };
|
||||
if (this.scope() === 'limit') body.limit = this.limit()!;
|
||||
if (this.scope() === 'selected') body.ids = this.selected();
|
||||
this.starting.set(true);
|
||||
this.actionError.set('');
|
||||
this.api.startAnalyzeJob(body).pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.starting.set(false)),
|
||||
).subscribe({
|
||||
next: (job) => this.storeJob(job),
|
||||
error: (error) => {
|
||||
const message = error.status === 409 ? 'Ya hay un análisis de EEG en curso.'
|
||||
: error.status === 404 ? 'No se encontró uno de los EEGs elegidos.' : 'No se pudo iniciar el análisis.';
|
||||
this.actionError.set(apiErrorMessage(error, message));
|
||||
if (error.status === 409) this.refreshJobs();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
recalculate(): void {
|
||||
if (this.busy()) return;
|
||||
this.recalculating.set(true);
|
||||
this.actionError.set('');
|
||||
this.cycleMessage.set('');
|
||||
this.api.recalculateTeaIndicators(this.choice()).pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.recalculating.set(false)),
|
||||
).subscribe({
|
||||
next: ({ pendiente }) => this.cycleMessage.set(pendiente ? 'Ciclo de indicadores solicitado. Pendiente de actualización.' : 'Solicitud de indicadores recibida.'),
|
||||
error: (error) => this.actionError.set(apiErrorMessage(error, 'No se pudo ejecutar el ciclo de indicadores.')),
|
||||
});
|
||||
}
|
||||
|
||||
chooseFile(event: Event): void {
|
||||
this.file.set((event.target as HTMLInputElement).files?.item(0) ?? null);
|
||||
this.uploaded.set(null);
|
||||
this.uploadError.set('');
|
||||
if (this.file() && !/\.edf$/i.test(this.file()!.name)) this.uploadError.set('Elige un archivo .edf.');
|
||||
if (!this.file()) { this.ados2File.set(null); this.viewOnly.set(false); }
|
||||
}
|
||||
|
||||
chooseAdos2(event: Event): void {
|
||||
const file = (event.target as HTMLInputElement).files?.item(0) ?? null;
|
||||
this.ados2File.set(file);
|
||||
this.uploadError.set(file && !/\.pdf$/i.test(file.name) ? 'Elige el informe ADOS-2 en PDF.' : '');
|
||||
}
|
||||
|
||||
/** Analyses the chosen EDF (and the ADOS-2 report) without storing anything and opens the record. */
|
||||
preview(): void {
|
||||
const file = this.file();
|
||||
if (!file || !this.canPreview()) return;
|
||||
this.uploading.set(true);
|
||||
this.uploadError.set('');
|
||||
this.api.previewEeg(file, this.ados2File() ?? undefined).pipe(
|
||||
switchMap((result) => this.tea.vistaPrevia(result.bundle).pipe(map((detalle) => ({ detalle, avisos: result.avisos })))),
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.uploading.set(false)),
|
||||
).subscribe({
|
||||
next: ({ detalle, avisos }) => {
|
||||
const data: EegPreviewData = { detalle, avisos, archivo: file.name };
|
||||
this.dialog.open(EegPreviewDialog, { data, maxWidth: '96vw', width: '1100px' });
|
||||
},
|
||||
error: (error) => this.uploadError.set(apiErrorMessage(error, 'No se pudo analizar el EDF.')),
|
||||
});
|
||||
}
|
||||
|
||||
upload(fileInput: HTMLInputElement): void {
|
||||
const file = this.file();
|
||||
if (!file || !this.canUpload()) return;
|
||||
this.uploading.set(true);
|
||||
this.uploadError.set('');
|
||||
this.uploaded.set(null);
|
||||
this.api.uploadEeg(file, this.patientId() ?? undefined).pipe(
|
||||
takeUntilDestroyed(this.destroyRef), finalize(() => this.uploading.set(false)),
|
||||
).subscribe({
|
||||
next: (result) => {
|
||||
this.uploaded.set(result);
|
||||
// The catalog lists canonical numeric keys as numbers and any other key (a UUID) as text.
|
||||
const rawId = result.eeg_id;
|
||||
const id = typeof rawId === 'string' && /^\d+$/.test(rawId) && String(Number(rawId)) === rawId
|
||||
? Number(rawId) : rawId;
|
||||
if (id !== null) this.selected.update((ids) => ids.includes(id) ? ids : [...ids, id]);
|
||||
this.scope.set('selected');
|
||||
this.revision.update((value) => value + 1);
|
||||
this.file.set(null);
|
||||
fileInput.value = '';
|
||||
},
|
||||
error: (error) => this.uploadError.set(apiErrorMessage(error, 'No se pudo subir el EDF.')),
|
||||
});
|
||||
}
|
||||
|
||||
private storeJob(job: AnalyzeJob): void {
|
||||
this.jobs.update((jobs) => [job, ...jobs.filter((item) => item.id !== job.id)]);
|
||||
}
|
||||
}
|
||||
|
||||
function positiveInteger(value: number | null): boolean {
|
||||
return value !== null && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<div class="controls">
|
||||
<label>Escenario
|
||||
<select [ngModel]="scenario()" (ngModelChange)="chooseScenario($event)" [disabled]="!scenarios().length">
|
||||
<option value="">Elige un escenario</option>
|
||||
@for (item of scenarios(); track item) { <option [value]="item">{{ item }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label>Versión
|
||||
<select [ngModel]="version()" (ngModelChange)="chooseVersion($event)" [disabled]="!versionOptions().length">
|
||||
<option [ngValue]="null">Elige una versión</option>
|
||||
@for (item of versionOptions(); track item) { <option [ngValue]="item">{{ item }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label>Métrica
|
||||
<select [ngModel]="metric()" (ngModelChange)="metric.set($event)" [disabled]="!metrics.hasValue() || !metrics.value().length">
|
||||
<option value="">Elige una métrica</option>
|
||||
@if (metrics.hasValue()) {
|
||||
@for (item of metrics.value(); track item) { <option [value]="item">{{ item }}</option> }
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<span tabindex="0" matTooltip="Próximamente"><button mat-stroked-button disabled>Probar en notebook</button></span>
|
||||
</div>
|
||||
@if (versions.isLoading() || metrics.isLoading() || curve.isLoading()) { <p role="status">Cargando línea base…</p> }
|
||||
@if (versions.error()) {
|
||||
<p role="alert">No se pudieron cargar las versiones.</p><button mat-button (click)="versions.reload()">Reintentar</button>
|
||||
} @else if (versions.hasValue() && !scenarios().length) { <p>No hay versiones de escenarios EEG.</p> }
|
||||
@if (metrics.error()) {
|
||||
<p role="alert">No se pudieron cargar las métricas de la línea base.</p><button mat-button (click)="metrics.reload()">Reintentar</button>
|
||||
} @else if (metrics.hasValue() && !metrics.value().length) { <p>Esta versión no tiene métricas con curvas.</p> }
|
||||
@if (curve.error()) {
|
||||
<p role="alert">No se pudo cargar la curva.</p><button mat-button (click)="curve.reload()">Reintentar</button>
|
||||
} @else if (curve.hasValue() && !figure()) { <p>La curva no tiene datos.</p> }
|
||||
|
||||
@if (figure(); as chart) {
|
||||
<app-plotly-chart [figure]="chart" [showNotes]="false" label="Curva por edad con mediana, bandas P5–P95 y P25–P75 y EEGs elegidos" />
|
||||
@if (curve.hasValue()) {
|
||||
@let data = curve.value();
|
||||
<details>
|
||||
<summary>Ver valores de la curva</summary>
|
||||
<div class="table-scroll">
|
||||
<table aria-label="Valores de la línea base">
|
||||
<thead><tr><th>Edad (meses)</th><th>P5</th><th>P25</th><th>Mediana</th><th>P75</th><th>P95</th></tr></thead>
|
||||
<tbody>
|
||||
@for (age of data.edad_meses; track $index) {
|
||||
<tr><td>{{ age }}</td><td>{{ data.p5[$index] }}</td><td>{{ data.p25[$index] }}</td>
|
||||
<td>{{ data.mediana[$index] }}</td><td>{{ data.p75[$index] }}</td><td>{{ data.p95[$index] }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
<h3>EEGs para comparar</h3>
|
||||
<app-eeg-picker [(selected)]="selected" />
|
||||
@if (eegMetrics.isLoading()) { <p role="status">Cargando métricas de los EEGs…</p> }
|
||||
@else if (eegMetrics.error()) {
|
||||
<p role="alert">No se pudieron cargar las métricas de los EEGs elegidos.</p>
|
||||
<button mat-button (click)="eegMetrics.reload()">Reintentar</button>
|
||||
} @else if (selected().length && metric() && !points().length) { <p>No hay EEGs elegidos con edad y valor para esta métrica.</p> }
|
||||
@if (points().length) {
|
||||
<details>
|
||||
<summary>Ver valores de los EEGs elegidos</summary>
|
||||
<div class="table-scroll">
|
||||
<table aria-label="Valores de los EEGs">
|
||||
<thead><tr><th>EEG</th><th>Edad (meses)</th><th>Valor</th><th>Clasificación</th></tr></thead>
|
||||
<tbody>
|
||||
@for (point of points(); track $index) {
|
||||
<tr><td>{{ point.id }}</td><td>{{ point.age }}</td><td>{{ point.value }}</td><td>{{ point.label }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
app-plotly-chart { --plot-height: 400px; --plot-min-width: 360px; }
|
||||
details { margin-block: .5rem; }
|
||||
@@ -0,0 +1,77 @@
|
||||
/** Pins version filtering, percentile curves and EEG overlays with mocked HTTP responses. */
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
|
||||
import { BaselineCheckComponent } from './baseline-check';
|
||||
|
||||
const baseline = '/governance/tea/baselines/eeg-posterior-rhythm/3';
|
||||
|
||||
describe('BaselineCheckComponent', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [
|
||||
provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react: vi.fn(), purge: vi.fn() }) },
|
||||
] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
|
||||
/** Sets up an EEG version, an unrelated TEA version and an empty catalog page. */
|
||||
async function create() {
|
||||
const fixture = TestBed.createComponent(BaselineCheckComponent);
|
||||
fixture.detectChanges();
|
||||
const versions = http.expectOne((req) => req.url === '/governance/model-versions');
|
||||
expect(versions.request.params.get('domain')).toBe('tea');
|
||||
versions.flush({ model_versions: [
|
||||
{ version: '3', tags: { scenario: 'eeg-posterior-rhythm' } },
|
||||
{ version: '9', tags: { scenario: 'riesgo-tea' } },
|
||||
] });
|
||||
http.expectOne((req) => req.url === '/governance/tea/eeg').flush([]);
|
||||
await fixture.whenStable();
|
||||
const step = fixture.componentInstance;
|
||||
expect(step.scenarios()).toEqual(['eeg-posterior-rhythm']);
|
||||
step.chooseScenario('eeg-posterior-rhythm');
|
||||
step.chooseVersion(3);
|
||||
fixture.detectChanges();
|
||||
http.expectOne(`${baseline}/metrics`).flush(['peak']);
|
||||
await fixture.whenStable();
|
||||
step.metric.set('peak');
|
||||
return fixture;
|
||||
}
|
||||
|
||||
/** Fails if the two percentile bands, medians or labeled high/low/inside points are lost. */
|
||||
it('draws the age curve and classifies the selected EEG values', async () => {
|
||||
const fixture = await create();
|
||||
const step = fixture.componentInstance;
|
||||
step.selected.set([8]);
|
||||
fixture.detectChanges();
|
||||
const curve = http.expectOne((req) => req.url === `${baseline}/curve`);
|
||||
expect(curve.request.params.get('metric')).toBe('peak');
|
||||
curve.flush({ edad_meses: [24, 36], p5: [1, 2], p25: [2, 3], mediana: [3, 4], metric: 'peak', p75: [4, 5], p95: [5, 6] });
|
||||
http.expectOne('/governance/tea/eeg/8/metrics').flush({ eeg_id: 8, age_months: 30, metrics: [
|
||||
{ name: 'peak', value: 0.5, outside: -1 },
|
||||
{ name: 'peak', value: 3, outside: 0 },
|
||||
{ name: 'peak', value: 8, outside: 1 },
|
||||
{ name: 'other', value: 7, outside: 1 },
|
||||
] });
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
const traces = step.figure()?.data;
|
||||
expect(traces?.map((trace) => trace['name'])).toEqual(['P5–P95', 'P25–P75', 'Mediana', 'Bajo', 'Dentro', 'Alto']);
|
||||
expect(traces?.[5]).toMatchObject({ x: [30], y: [8], marker: { symbol: 'triangle-up' } });
|
||||
expect(fixture.nativeElement.textContent).toContain('Ver valores de la curva');
|
||||
});
|
||||
|
||||
/** Fails if a missing curve appears empty without surfacing the HTTP error and retry control. */
|
||||
it('shows a retry when a curve is unavailable', async () => {
|
||||
const fixture = await create();
|
||||
fixture.detectChanges();
|
||||
http.expectOne((req) => req.url === `${baseline}/curve`).flush(null, { status: 404, statusText: 'Not Found' });
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('No se pudo cargar la curva.');
|
||||
expect(fixture.nativeElement.textContent).toContain('Reintentar');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Component, ElementRef, computed, inject, model, signal } from '@angular/core';
|
||||
import { rxResource } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { forkJoin } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
|
||||
import { GovernanceApi } from '../../api/governance.api';
|
||||
import { TeaEegApi } from '../../api/tea-eeg.api';
|
||||
import { EegId, EegMetrics } from '../../api/tea-eeg.types';
|
||||
import { EegPicker } from '../eeg-picker/eeg-picker';
|
||||
import { baselineFigure, overlayPoints } from './baseline-figure';
|
||||
|
||||
@Component({
|
||||
selector: 'app-baseline-check',
|
||||
imports: [EegPicker, FormsModule, MatButtonModule, MatTooltipModule, PlotlyChart],
|
||||
templateUrl: './baseline-check.html',
|
||||
styleUrls: ['../eeg-step.scss', './baseline-check.scss'],
|
||||
})
|
||||
export class BaselineCheckComponent {
|
||||
private readonly api = inject(TeaEegApi);
|
||||
private readonly governance = inject(GovernanceApi);
|
||||
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
readonly scenario = signal('');
|
||||
readonly version = signal<number | null>(null);
|
||||
readonly metric = signal('');
|
||||
readonly selected = model<EegId[]>([]);
|
||||
readonly versions = rxResource({
|
||||
stream: () => this.governance.listModelVersions({ domain: 'tea' }),
|
||||
});
|
||||
readonly eegVersions = computed(() => this.versions.hasValue()
|
||||
? this.versions.value().model_versions.filter((version) => version.tags.scenario?.startsWith('eeg-')) : []);
|
||||
readonly scenarios = computed(() => [...new Set(this.eegVersions().map((version) => version.tags.scenario!))].sort());
|
||||
readonly versionOptions = computed(() => [...new Set(this.eegVersions()
|
||||
.filter((version) => version.tags.scenario === this.scenario())
|
||||
.map((version) => Number(version.version)).filter((version) => Number.isSafeInteger(version) && version > 0))]
|
||||
.sort((a, b) => b - a));
|
||||
readonly metrics = rxResource({
|
||||
params: () => {
|
||||
const version = this.version();
|
||||
return version === null ? undefined : { scenario: this.scenario(), version };
|
||||
},
|
||||
stream: ({ params }) => this.api.baselineMetrics(params.scenario, params.version),
|
||||
});
|
||||
readonly curve = rxResource({
|
||||
params: () => {
|
||||
const version = this.version();
|
||||
const metric = this.metric();
|
||||
return version === null || !metric ? undefined : { scenario: this.scenario(), version, metric };
|
||||
},
|
||||
stream: ({ params }) => this.api.baselineCurve(params.scenario, params.version, params.metric),
|
||||
});
|
||||
readonly eegMetrics = rxResource({
|
||||
params: () => this.selected().length && this.metric() ? this.selected() : undefined,
|
||||
stream: ({ params }) => forkJoin(params.map((id) => this.api.eegMetrics(id))),
|
||||
defaultValue: [] as EegMetrics[],
|
||||
});
|
||||
readonly points = computed(() => overlayPoints(this.eegMetrics.hasValue() ? this.eegMetrics.value() : [], this.metric()));
|
||||
readonly figure = computed(() => {
|
||||
if (!this.curve.hasValue() || !this.curve.value().edad_meses.length) return null;
|
||||
const style = getComputedStyle(this.host.nativeElement);
|
||||
return baselineFigure(this.curve.value(), this.points(), (token) => style.getPropertyValue(`--eeg-${token}`).trim(), style.color);
|
||||
});
|
||||
|
||||
chooseScenario(scenario: string): void {
|
||||
this.scenario.set(scenario);
|
||||
this.chooseVersion(null);
|
||||
}
|
||||
|
||||
chooseVersion(version: number | null): void {
|
||||
this.version.set(version);
|
||||
this.metric.set('');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { PlotlyFigure } from '../../../features/indicadores/indicadores.models';
|
||||
import { BaselineCurve, EegMetrics } from '../../api/tea-eeg.types';
|
||||
|
||||
const OUTSIDE = [
|
||||
{ flag: -1, label: 'Bajo', color: 'blue', symbol: 'triangle-down' },
|
||||
{ flag: 0, label: 'Dentro', color: 'purple', symbol: 'circle' },
|
||||
{ flag: 1, label: 'Alto', color: 'vermilion', symbol: 'triangle-up' },
|
||||
{ flag: null, label: 'Sin clasificación', color: 'axis', symbol: 'diamond-open' },
|
||||
] as const;
|
||||
|
||||
export function overlayPoints(eegs: EegMetrics[], metric: string) {
|
||||
return eegs.flatMap((eeg) => eeg.age_months === null ? [] : eeg.metrics
|
||||
.filter((item) => item.name === metric && Number.isFinite(item.value))
|
||||
.map((item) => ({
|
||||
id: eeg.eeg_id,
|
||||
age: eeg.age_months!,
|
||||
value: item.value,
|
||||
outside: item.outside,
|
||||
label: OUTSIDE.find((group) => group.flag === item.outside)?.label,
|
||||
})));
|
||||
}
|
||||
|
||||
export function baselineFigure(
|
||||
curve: BaselineCurve, points: ReturnType<typeof overlayPoints>, color: (token: string) => string, ink: string,
|
||||
): PlotlyFigure {
|
||||
const x = curve.edad_meses;
|
||||
const band = (low: number[], high: number[], name: string, token: string) => ({
|
||||
type: 'scatter', mode: 'lines', name, x: [...x, ...[...x].reverse()], y: [...high, ...[...low].reverse()],
|
||||
fill: 'toself', fillcolor: color(token), line: { width: 0 }, hoverinfo: 'skip',
|
||||
});
|
||||
return {
|
||||
data: [
|
||||
band(curve.p5, curve.p95, 'P5–P95', 'band-outer'),
|
||||
band(curve.p25, curve.p75, 'P25–P75', 'band-inner'),
|
||||
{ type: 'scatter', mode: 'lines', name: 'Mediana', x, y: curve.mediana, line: { color: color('blue'), width: 2 } },
|
||||
...OUTSIDE.flatMap(({ flag, label, color: token, symbol }) => {
|
||||
const group = points.filter((point) => point.outside === flag);
|
||||
return group.length ? [{
|
||||
type: 'scatter', mode: 'markers', name: label,
|
||||
x: group.map((point) => point.age), y: group.map((point) => point.value),
|
||||
text: group.map((point) => `EEG ${point.id}`), marker: { color: token === 'axis' ? ink : color(token), symbol, size: 10 },
|
||||
}] : [];
|
||||
}),
|
||||
],
|
||||
layout: {
|
||||
autosize: true, height: 400, margin: { l: 65, r: 20, t: 20, b: 100 },
|
||||
paper_bgcolor: 'transparent', plot_bgcolor: 'transparent', font: { color: ink },
|
||||
xaxis: { title: { text: 'Edad (meses)' }, showgrid: false, zeroline: false },
|
||||
yaxis: { title: { text: curve.metric }, showgrid: false, zeroline: false },
|
||||
legend: { orientation: 'h', y: -.22 },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<section class="health">
|
||||
<div class="health__toolbar">
|
||||
<h2 class="health__title">Estado del clúster</h2>
|
||||
<span class="health__spacer"></span>
|
||||
<span class="health__latency">
|
||||
@if (latencyMs() != null) {
|
||||
Latencia: {{ latencyMs() }} ms
|
||||
} @else {
|
||||
Latencia: sin datos
|
||||
}
|
||||
</span>
|
||||
<button mat-button type="button" (click)="refresh()" [disabled]="loading()">
|
||||
<mat-icon aria-hidden="true">refresh</mat-icon>Verificar
|
||||
</button>
|
||||
<button mat-button type="button" color="primary" class="health__dashboard" [disabled]="!dashboardEnabled()" [matTooltip]="dashboardTooltip()" (click)="openDashboard()">
|
||||
<mat-icon aria-hidden="true">open_in_new</mat-icon>Abrir dashboard de Dask
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (loadError(); as error) {
|
||||
<p class="health__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
|
||||
}
|
||||
|
||||
<ul class="health__rows">
|
||||
@for (row of rows(); track row.key) {
|
||||
<li class="health__row" [ngClass]="'health__row--' + row.state">
|
||||
<span class="health__check">
|
||||
<mat-icon aria-hidden="true">{{ iconFor(row.state) }}</mat-icon>{{ estados[row.state] }}
|
||||
</span>
|
||||
<span class="health__label">{{ row.label }}</span>
|
||||
<span class="health__detail">{{ row.detail }}</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user