Compare commits

...

26 Commits

Author SHA1 Message Date
Angel Capetillo Zavala fb54cfb188 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:41 -06:00
alberto 4e9b25bd8f feat(tea): read the age-norm curve, the age at the EEG and the ADOS-2 relation from the WebApi's FHIR answer 2026-11-21 11:17:59 -06:00
alberto 68e2930e65 chore(tea): drop the local simulated-server mode; TEA follow-up reads only the WebApi 2026-11-21 01:30:45 -06:00
Angel Capetillo Zavala bb957ec6a4 fix(indicadores): format the hover text of CaCu's donuts per sector 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 02e28e624b feat(indicadores): read CaCu category groups and stratified compositions from FHIR 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 08161db1c4 feat(indicadores): map CaCu measures to the indicator ids the page reads 2026-11-21 01:27:59 -06:00
ulises fa029d69b8 Seguimiento TEA: gráfica de la norma por edad con el paciente
El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas
5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 67ae7f482f TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
ulises 304c563845 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del
paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado.
El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración
«simulado» de Angular) es solo para trabajar en local.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 00:50:10 -06:00
AlbertoPMDM ef4f606648 fix(tea): one card per EEG metric and the electrode map within its column
(cherry picked from commit b53322ed72)
2026-11-20 21:56:05 -06:00
AlbertoPMDM b53322ed72 fix(tea): one card per EEG metric and the electrode map within its column 2026-11-20 19:52:10 -06:00
Manuel Aurrecoechea Castillo c32d2b6012 feat(indicadores): show full domain names and share CaMa's summary
CaCu and TEA use the same menu labels and compact summary layout as cáncer de mama.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 19:28:27 -06:00
Angel Capetillo Zavala c2c6d9ef47 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:44:48 -06:00
angel d4d3ea3837 Merge pull request 'Restore published CaMa histopathology and mammography counts' (#14) from fix/cama-reversion-selectiva into dev 2026-11-20 10:03:41 -06:00
Angel Capetillo Zavala 3385df4ba3 Merge current WebApp dev into the CaMa selective rollback 2026-11-20 09:57:32 -06:00
Manuel Aurrecoechea Castillo 96b1cabb5a feat(cama): space the opportunity strip, share its period and unify history lines
The section sat flush against its cards, each card repeated the period, the history selector was taller than the summary, and each CaMa line used a different color.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 09:49:32 -06:00
Angel Capetillo Zavala 366591f247 fix(cama): restore published histopathology and mammography counts 2026-11-20 09:07:38 -06:00
angel 241631b884 Merge pull request 'Finalize CaMa wording, demo mammography counts and histologic classification' (#13) from feature/cama-clasificacion-histologica into dev 2026-11-20 00:52:29 -06:00
Angel Capetillo Zavala 6c063344a3 feat(cama): adjust summary wording, double mastography counts and classify histologic types
Reword the histopathologic confirmation note, the BI-RADS 4, 5 or 6 titles and the
radiologic interpretation time title. Show twice the BI-RADS 4, 5 or 6 mastography
counts in the FHIR and base data services. Add the histologic type classification
and a follow-up table column that appears only when a row carries tipo_histologico.
2026-11-20 00:32:27 -06:00
angel 2f5b1ce1f2 Merge pull request 'Feature/cama audit histopathology demo' (#12) from feature/cama-audit-histopathology-demo into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/12
2026-11-19 19:45:53 -06:00
Angel Capetillo Zavala 56b3ac6b0c feat(cama): add synthetic histopathology breakdown for demo 2026-11-19 19:36:18 -06:00
Angel Capetillo Zavala f6603ae76e fix(cama): align BI-RADS labels and remove historical detection chart 2026-11-19 19:04:22 -06:00
Manuel Aurrecoechea Castillo 21ae95b5ed 20261119 CaMa: ayuda en cada dona de BI-RADS
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:11:20 -06:00
Manuel Aurrecoechea Castillo ce2e86c045 20261119 CaMa: cada dona de BI-RADS lleva su título y la categoría más alta
El resumen ya no repite el porcentaje publicado; pacientes y mastografías se leen en su propia gráfica.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:05:40 -06:00
angel 0f8eb0ec94 Merge pull request 'Add unavailable CaMa diagnosis-to-treatment card' (#11) from feature/cama-diagnosis-to-treatment-card into dev 2026-11-19 17:51:43 -06:00
AlbertoPMDM 04795a09cc feat(tea): read the EEG analysis's verdict, quality checks and age baselines 2026-11-19 15:43:27 -06:00
72 changed files with 5374 additions and 647 deletions
+3 -3
View File
@@ -41,7 +41,7 @@ describe('Encabezado del marco', () => {
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]); const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.path)]);
for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`); for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`);
}); });
it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => { it.each([['tea', 'Trastorno del espectro autista'], ['cacu', 'Cáncer cervicouterino'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
await ir('/indicadores/' + dominio); await ir('/indicadores/' + dominio);
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores'); expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾'); expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
@@ -60,7 +60,7 @@ describe('Encabezado del marco', () => {
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => { it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
await ir('/indicadores/cama'); await ir('/indicadores/cama');
const items = await abrirMenu(); const items = await abrirMenu();
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']); expect(items.map(a => a.textContent?.trim())).toEqual(['Trastorno del espectro autista', 'Cáncer cervicouterino']);
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']); expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
expect(selector()!.getAttribute('aria-expanded')).toBe('true'); expect(selector()!.getAttribute('aria-expanded')).toBe('true');
}); });
@@ -69,7 +69,7 @@ describe('Encabezado del marco', () => {
const items = await abrirMenu(); const items = await abrirMenu();
items[1].click(); await fixture.whenStable(); fixture.detectChanges(); items[1].click(); await fixture.whenStable(); fixture.detectChanges();
expect(router.url).toBe('/indicadores/cacu'); expect(router.url).toBe('/indicadores/cacu');
expect(selector()!.textContent).toContain('CaCu'); expect(selector()!.textContent).toContain('Cáncer cervicouterino');
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain. // The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
const ubicacion = TestBed.inject(Location); const ubicacion = TestBed.inject(Location);
ubicacion.back(); await new Promise(r => setTimeout(r, 100)); ubicacion.back(); await new Promise(r => setTimeout(r, 100));
+29 -6
View File
@@ -117,7 +117,8 @@
.domain-selector--espera { .domain-selector--espera {
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto; align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap; max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
min-height: 40px; padding: 0 16px; white-space: nowrap;
} }
/* Session exit: the same action look as the home buttons, in header size. */ /* Session exit: the same action look as the home buttons, in header size. */
@@ -160,9 +161,31 @@
width: 18px; width: 18px;
} }
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed. // Full domain names need their own track. On a wide header they sit beside the title;
@media (max-width: 599px) { // below 900px the name takes a row of its own so the logo and the exit stay together.
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; } .app-shell--indicadores .site-header__content {
.app-shell--indicadores .brand { margin-inline-end: auto; } display: grid;
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; } grid-template-columns: auto minmax(0, 1fr) auto auto;
grid-template-areas: "brand title domain salir";
align-items: center;
column-gap: 16px;
row-gap: 8px;
padding-block: 8px;
}
.app-shell--indicadores .brand { grid-area: brand; }
.app-shell--indicadores .platform-title { grid-area: title; margin: 0; overflow-wrap: normal; }
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { grid-area: domain; justify-self: end; }
.app-shell--indicadores .site-header__salir { grid-area: salir; margin-inline-start: 0; }
@media (max-width: 900px) {
.app-shell--indicadores .site-header__content {
grid-template-columns: auto minmax(0, 1fr);
grid-template-areas:
"brand salir"
"domain domain"
"title title";
}
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { justify-self: start; white-space: normal; }
.app-shell--indicadores .platform-title { font-size: 1.125rem; }
} }
+1 -1
View File
@@ -93,7 +93,7 @@ describe('App', () => {
it('el encabezado no ofrece los otros dominios', async () => { it('el encabezado no ofrece los otros dominios', async () => {
const page = await render('/indicadores/cacu'); const page = await render('/indicadores/cacu');
expect(page.querySelector('app-domain-selector')).toBeNull(); expect(page.querySelector('app-domain-selector')).toBeNull();
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('CaCu'); expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('Cáncer cervicouterino');
}); });
}); });
+3 -1
View File
@@ -38,7 +38,9 @@ export class App {
protected readonly usuario = this.auth.usuario; protected readonly usuario = this.auth.usuario;
protected readonly title = 'Plataforma de Indicadores'; protected readonly title = 'Plataforma de Indicadores';
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' }; protected readonly domainLabels: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
};
private readonly url = toSignal(this.router.events.pipe( private readonly url = toSignal(this.router.events.pipe(
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url }); filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
/** On an indicators page the header names its domain and switches to the others. */ /** On an indicators page the header names its domain and switches to the others. */
@@ -13,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
import { ImportFlow } from '../domain/import-flow'; import { ImportFlow } from '../domain/import-flow';
export const DOMAINS: { id: Domain; label: string; description: string }[] = [ export const DOMAINS: { id: Domain; label: string; description: string }[] = [
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' }, { id: 'cacu', label: 'Cáncer cervicouterino', description: 'Cáncer cervicouterino' },
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' }, { id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' }, { id: 'tea', label: 'Trastorno del espectro autista', description: 'Trastorno del espectro autista' },
]; ];
/** /**
+7
View File
@@ -1,10 +1,17 @@
:host { display: contents; } :host { display: contents; }
.domain-selector { .domain-selector {
flex: 0 0 auto; flex: 0 0 auto;
max-width: 100%;
height: auto;
min-height: 40px;
background-color: var(--issste-accent); background-color: var(--issste-accent);
color: var(--issste-text); color: var(--issste-text);
font-weight: 700; font-weight: 700;
line-height: 1.2;
white-space: nowrap; white-space: nowrap;
} }
@media (max-width: 900px) {
.domain-selector { white-space: normal; text-align: start; padding-block: 8px; }
}
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); } .domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
+3 -3
View File
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
export interface Quantity { value?: number; unit?: string } export interface Quantity { value?: number; unit?: string }
export interface Extension { export interface Extension {
url: string; url: string;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string }; valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[]; extension?: Extension[];
} }
@@ -30,9 +30,9 @@ export function code(concept: Concept | undefined): string | undefined {
export function display(concept: Concept | undefined): string | undefined { export function display(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.display ?? concept?.text; return concept?.coding?.[0]?.display ?? concept?.text;
} }
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL). // The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
export function codeIn(concept: Concept | undefined, system: string): string | undefined { export function codeIn(concept: Concept | undefined, system: string): string | undefined {
const url = system.includes('://') ? system : CODE_SYSTEM + system; const url = system.includes(':') ? system : CODE_SYSTEM + system;
return concept?.coding?.find(c => c.system === url)?.code; return concept?.coding?.find(c => c.system === url)?.code;
} }
// The extensions named `name` (the last segment of their URL). // The extensions named `name` (the last segment of their URL).
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,8 +1,8 @@
{ {
"cacu/CACU-CONFIRMACION-CITOLOGIA": { "cacu/CACU-CONFIRMACION-CITOLOGIA": {
"id": "CACU_CONFIRMACION_CITOLOGIA", "id": "cacu_confirmacion_citologia",
"indicador": { "indicador": {
"id": "CACU_CONFIRMACION_CITOLOGIA", "id": "cacu_confirmacion_citologia",
"version": "0.1.2", "version": "0.1.2",
"titulo": "Tasa de confirmación histopatológica", "titulo": "Tasa de confirmación histopatológica",
"contrato": "C2", "contrato": "C2",
@@ -19,7 +19,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "CACU_CONFIRMACION_CITOLOGIA", "id": "cacu_confirmacion_citologia",
"version": "0.1.2", "version": "0.1.2",
"descripcion": "De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un grado mientras lleguen reportes.", "descripcion": "De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un grado mientras lleguen reportes.",
"ficha": { "ficha": {
@@ -41,7 +41,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "CACU_CONFIRMACION_CITOLOGIA", "id": "cacu_confirmacion_citologia",
"titulo": "Tasa de confirmación histopatológica", "titulo": "Tasa de confirmación histopatológica",
"version": "0.1.2", "version": "0.1.2",
"contrato": "C2", "contrato": "C2",
@@ -80,51 +80,14 @@
"filas": [] "filas": []
}, },
"citologia_alto_grado": { "citologia_alto_grado": {
"id": "CACU_CONFIRMACION_CITOLOGIA", "error": "Categoría no declarada en el estrato"
"titulo": "Tasa de confirmación histopatológica",
"version": "0.1.2",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
"2025-S2"
],
"estrato": "citologia_alto_grado",
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [],
"reportes": [
{
"periodo": "2021-S1",
"report_id": 35,
"periodo_inicio": "2021-01-01",
"periodo_fin": "2021-07-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:24.181623+00:00"
},
{
"periodo": "2025-S2",
"report_id": 44,
"periodo_inicio": "2025-07-01",
"periodo_fin": "2026-01-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:24.682752+00:00"
}
],
"filas": []
} }
} }
}, },
"cacu/CACU-DIAS-TOMA-DIAGNOSTICO": { "cacu/CACU-DIAS-TOMA-DIAGNOSTICO": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO", "id": "cacu_dias_toma_diagnostico",
"indicador": { "indicador": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO", "id": "cacu_dias_toma_diagnostico",
"version": "0.2.3", "version": "0.2.3",
"titulo": "Tiempo de tamizaje a diagnóstico", "titulo": "Tiempo de tamizaje a diagnóstico",
"contrato": "C3r", "contrato": "C3r",
@@ -139,7 +102,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO", "id": "cacu_dias_toma_diagnostico",
"version": "0.2.3", "version": "0.2.3",
"descripcion": "Días naturales de la toma de cada citología del periodo a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, 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.", "descripcion": "Días naturales de la toma de cada citología del periodo a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, 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.",
"ficha": { "ficha": {
@@ -171,7 +134,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO", "id": "cacu_dias_toma_diagnostico",
"titulo": "Tiempo de tamizaje a diagnóstico", "titulo": "Tiempo de tamizaje a diagnóstico",
"version": "0.2.3", "version": "0.2.3",
"contrato": "C3r", "contrato": "C3r",
@@ -239,9 +202,9 @@
} }
}, },
"cacu/CACU-EU-TIEMPO-REPORTE": { "cacu/CACU-EU-TIEMPO-REPORTE": {
"id": "CACU_EU_TIEMPO_REPORTE", "id": "cacu_eu_tiempo_reporte",
"indicador": { "indicador": {
"id": "CACU_EU_TIEMPO_REPORTE", "id": "cacu_eu_tiempo_reporte",
"version": "0.2.1", "version": "0.2.1",
"titulo": "Días de la toma de la citología a su resultado", "titulo": "Días de la toma de la citología a su resultado",
"contrato": "C3r", "contrato": "C3r",
@@ -256,7 +219,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "CACU_EU_TIEMPO_REPORTE", "id": "cacu_eu_tiempo_reporte",
"version": "0.2.1", "version": "0.2.1",
"descripcion": "Días naturales de la toma de cada citología del periodo a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.", "descripcion": "Días naturales de la toma de cada citología del periodo a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
"ficha": { "ficha": {
@@ -288,7 +251,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "CACU_EU_TIEMPO_REPORTE", "id": "cacu_eu_tiempo_reporte",
"titulo": "Días de la toma de la citología a su resultado", "titulo": "Días de la toma de la citología a su resultado",
"version": "0.2.1", "version": "0.2.1",
"contrato": "C3r", "contrato": "C3r",
@@ -356,9 +319,9 @@
} }
}, },
"cacu/CACU-EU13": { "cacu/CACU-EU13": {
"id": "CACU_EU13", "id": "cacu_eu13",
"indicador": { "indicador": {
"id": "CACU_EU13", "id": "cacu_eu13",
"version": "0.3.2", "version": "0.3.2",
"titulo": "Tasa de detección histopatológica", "titulo": "Tasa de detección histopatológica",
"contrato": "C1", "contrato": "C1",
@@ -376,7 +339,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "CACU_EU13", "id": "cacu_eu13",
"version": "0.3.2", "version": "0.3.2",
"descripcion": "De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3), carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.", "descripcion": "De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3), carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.",
"ficha": { "ficha": {
@@ -408,7 +371,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "CACU_EU13", "id": "cacu_eu13",
"titulo": "Tasa de detección histopatológica", "titulo": "Tasa de detección histopatológica",
"version": "0.3.2", "version": "0.3.2",
"contrato": "C1", "contrato": "C1",
@@ -474,7 +437,7 @@
] ]
}, },
"grupo_edad": { "grupo_edad": {
"id": "CACU_EU13", "id": "cacu_eu13",
"titulo": "Tasa de detección histopatológica", "titulo": "Tasa de detección histopatológica",
"version": "0.3.2", "version": "0.3.2",
"contrato": "C1", "contrato": "C1",
@@ -592,7 +555,7 @@
] ]
}, },
"estatus_seguimiento": { "estatus_seguimiento": {
"id": "CACU_EU13", "id": "cacu_eu13",
"titulo": "Tasa de detección histopatológica", "titulo": "Tasa de detección histopatológica",
"version": "0.3.2", "version": "0.3.2",
"contrato": "C1", "contrato": "C1",
@@ -652,9 +615,9 @@
} }
}, },
"cacu/CACU-EU7": { "cacu/CACU-EU7": {
"id": "CACU_EU7", "id": "cacu_eu7",
"indicador": { "indicador": {
"id": "CACU_EU7", "id": "cacu_eu7",
"version": "0.3.3", "version": "0.3.3",
"titulo": "Distribución de resultados citológicos", "titulo": "Distribución de resultados citológicos",
"contrato": "C2", "contrato": "C2",
@@ -672,7 +635,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "CACU_EU7", "id": "cacu_eu7",
"version": "0.3.3", "version": "0.3.3",
"descripcion": "Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.", "descripcion": "Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.",
"ficha": { "ficha": {
@@ -694,7 +657,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "CACU_EU7", "id": "cacu_eu7",
"titulo": "Distribución de resultados citológicos", "titulo": "Distribución de resultados citológicos",
"version": "0.3.3", "version": "0.3.3",
"contrato": "C2", "contrato": "C2",
@@ -733,91 +696,17 @@
"filas": [] "filas": []
}, },
"grupo_edad": { "grupo_edad": {
"id": "CACU_EU7", "error": "Categoría no declarada en el estrato"
"titulo": "Distribución de resultados citológicos",
"version": "0.3.3",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
"2025-S2"
],
"estrato": "grupo_edad",
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [],
"reportes": [
{
"periodo": "2021-S1",
"report_id": 83,
"periodo_inicio": "2021-01-01",
"periodo_fin": "2021-07-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:29.557925+00:00"
},
{
"periodo": "2025-S2",
"report_id": 92,
"periodo_inicio": "2025-07-01",
"periodo_fin": "2026-01-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:31.081202+00:00"
}
],
"filas": []
}, },
"estatus_seguimiento": { "estatus_seguimiento": {
"id": "CACU_EU7", "error": "Categoría no declarada en el estrato"
"titulo": "Distribución de resultados citológicos",
"version": "0.3.3",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
"2025-S2"
],
"estrato": "estatus_seguimiento",
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [],
"reportes": [
{
"periodo": "2021-S1",
"report_id": 83,
"periodo_inicio": "2021-01-01",
"periodo_fin": "2021-07-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:29.557925+00:00"
},
{
"periodo": "2025-S2",
"report_id": 92,
"periodo_inicio": "2025-07-01",
"periodo_fin": "2026-01-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:31.081202+00:00"
}
],
"filas": []
} }
} }
}, },
"cacu/CACU-RIESGO-BANDA": { "cacu/CACU-RIESGO-BANDA": {
"id": "CACU_RIESGO_BANDA", "id": "cacu_riesgo_banda",
"indicador": { "indicador": {
"id": "CACU_RIESGO_BANDA", "id": "cacu_riesgo_banda",
"version": "0.1.0", "version": "0.1.0",
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+", "titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
"contrato": "C2", "contrato": "C2",
@@ -831,7 +720,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "CACU_RIESGO_BANDA", "id": "cacu_riesgo_banda",
"version": "0.1.0", "version": "0.1.0",
"descripcion": "Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene evaluación confirmada en ese lote.", "descripcion": "Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene evaluación confirmada en ese lote.",
"ficha": { "ficha": {
@@ -853,7 +742,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "CACU_RIESGO_BANDA", "id": "cacu_riesgo_banda",
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+", "titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
"version": "0.1.0", "version": "0.1.0",
"contrato": "C2", "contrato": "C2",
@@ -894,9 +783,9 @@
} }
}, },
"cacu/IND1": { "cacu/IND1": {
"id": "IND1", "id": "ind1",
"indicador": { "indicador": {
"id": "IND1", "id": "ind1",
"version": "0.3.2", "version": "0.3.2",
"titulo": "Pacientes con citología anómala", "titulo": "Pacientes con citología anómala",
"contrato": "C1", "contrato": "C1",
@@ -911,7 +800,7 @@
"filtros": [] "filtros": []
}, },
"metadatos": { "metadatos": {
"id": "IND1", "id": "ind1",
"version": "0.3.2", "version": "0.3.2",
"descripcion": "Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG, ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.", "descripcion": "Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG, ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.",
"ficha": { "ficha": {
@@ -943,7 +832,7 @@
}, },
"datos": { "datos": {
"total": { "total": {
"id": "IND1", "id": "ind1",
"titulo": "Pacientes con citología anómala", "titulo": "Pacientes con citología anómala",
"version": "0.3.2", "version": "0.3.2",
"contrato": "C1", "contrato": "C1",
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro'); expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull(); expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); expect(fixture.nativeElement.querySelector('.catalog-metadata')).toBeNull();
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
// The internal panel heading is deliberately visually hidden and retains identity. // The internal panel heading is deliberately visually hidden and retains identity.
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement; const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove()); copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
@@ -30,19 +30,21 @@ import { parConteos } from './indicadores-conteos-pareados';
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados], imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
template: ` template: `
<mat-card> <mat-card>
<header> @if (!conteos) {
<div class="card-identity"> <header>
<h2 [id]="titleId" tabindex="-1">{{ tituloVisible }}</h2> <div class="card-identity">
</div> <h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</header> </div>
</header>
}
@if (!sobrio) { @if (!sobrio) {
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned" <button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + tituloVisible" [attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
(click)="pinChanged.emit()"> (click)="pinChanged.emit()">
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }} <mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button> </button>
} }
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId"> <div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="conteos ? null : titleId">
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> } @if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
@if (isEu7) { @if (isEu7) {
<div #visibilityRegion class="eu7-region"> <div #visibilityRegion class="eu7-region">
@@ -62,7 +64,7 @@ import { parConteos } from './indicadores-conteos-pareados';
</div> </div>
} @else if (conteos; as par) { } @else if (conteos; as par) {
<div #visibilityRegion class="conteos-region"> <div #visibilityRegion class="conteos-region">
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" [metadataAttempt]="metadataAttempt" (metadataRequested)="loadMetadata()" /> <app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
</div> </div>
} @else if (selectedFigure) { } @else if (selectedFigure) {
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual"> <div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@@ -126,7 +128,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
private metadataSubscription?: Subscription; private metadataSubscription?: Subscription;
private metadataKey = ''; private metadataKey = '';
metadata?: IndicadorMetadatos; metadata?: IndicadorMetadatos;
metadataAttempt = 0;
private activatedKey = ''; private activatedKey = '';
constructor() { constructor() {
effect(() => { effect(() => {
@@ -134,12 +135,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.indicador && this.applied) untracked(() => this.updateNumeric()); if (this.indicador && this.applied) untracked(() => this.updateNumeric());
}); });
} }
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup. // Every domain follows CaMa's mockup: no pin, representation selector or figure count.
get sobrio() { return this.dominio === 'cama'; } get sobrio() { return true; }
// The published title keeps «individual»; the card does not.
get tituloVisible() {
return this.indicador.id === 'cama_birads_456_mastografia' ? this.indicador.titulo.replace(' individual', '') : this.indicador.titulo;
}
get pair() { return dualFigures(this.indicador); } get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
@@ -225,7 +222,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.metadataKey !== key) return; if (this.metadataKey !== key) return;
if (!value) this.metadataKey = ''; if (!value) this.metadataKey = '';
this.metadata = value; this.metadata = value;
this.metadataAttempt++;
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
}); });
} }
@@ -1,25 +1,4 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)"> <section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<div class="conteos-head">
<div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
<button type="button" class="help-icon" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
@if (helpOpen) {
<div class="methodology" role="tooltip">
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
<h3>Dona por categoría</h3>
@if (donutGuide; as guide) {
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
</section>
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las donas muestran ambos conteos por categoría de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
</section>
</div>
}
</div>
</div>
@switch (status()) { @switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> } @case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> } @case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
@@ -28,6 +7,8 @@
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> } @case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
} }
@if (status() === 'ready' && model; as m) { @if (status() === 'ready' && model; as m) {
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
@if (pages.length > 1) { @if (pages.length > 1) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo"> <nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button> <button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
@@ -36,15 +17,35 @@
</nav> </nav>
} }
<div class="figures"> <div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3> <section class="figure">
<div class="figure-head">
<h3>{{ tituloMastografias }}</h3>
<div class="help" (mouseenter)="openHelp('examenes')" (mouseleave)="hideHelp('examenes')" (focusin)="openHelp('examenes')" (focusout)="onHelpFocusOut('examenes', $event)">
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'"
[attr.aria-describedby]="helpWhich === 'examenes' ? 'cama-birads-ayuda-mastografias' : null" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
@if (helpWhich === 'examenes') {
<div class="methodology" id="cama-birads-ayuda-mastografias" role="tooltip">Cada mastografía cuenta en su propia categoría.</div>
}
</div>
</div>
@if (total) { @if (total) {
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" /> <app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="tituloMastografias" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> } } @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> } @if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section> </section>
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} por categoría, {{ m.periodo }}</h3> <section class="figure">
<div class="figure-head">
<h3>{{ tituloPacientes }}</h3>
<div class="help" (mouseenter)="openHelp('pacientes')" (mouseleave)="hideHelp('pacientes')" (focusin)="openHelp('pacientes')" (focusout)="onHelpFocusOut('pacientes', $event)">
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'"
[attr.aria-describedby]="helpWhich === 'pacientes' ? 'cama-birads-ayuda-pacientes' : null" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
@if (helpWhich === 'pacientes') {
<div class="methodology" id="cama-birads-ayuda-pacientes" role="tooltip">La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.</div>
}
</div>
</div>
@if (totalPacientes) { @if (totalPacientes) {
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="indicador.titulo + ', dona de pacientes por categoría BI-RADS, ' + m.periodo" /> <app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="tituloPacientes" />
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> } } @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> } @if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
</section> </section>
@@ -52,7 +53,7 @@
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> } @for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary> <details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0"> <div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption> <table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más alta) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead> <thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody> <tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
</table> </table>
@@ -3,19 +3,17 @@
p, h3, summary { overflow-wrap: anywhere; } p, h3, summary { overflow-wrap: anywhere; }
.applied-summary, .note { color: var(--issste-text-secondary); } .applied-summary, .note { color: var(--issste-text-secondary); }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } .methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.reading-guide h3 { margin: 0 0 .25rem; } .figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; } .figure-head h3 { margin: 0; }
.reading-guide + .reading-guide { margin-top: 1rem; } .help { display: flex; flex: none; justify-content: flex-end; }
.reading-guide li + li { margin-top: .25rem; } .help .methodology { position: absolute; z-index: 8; inset-block-start: calc(100% + .35rem); inset-inline-end: 0;
.help { position: relative; display: flex; justify-content: flex-end; } box-sizing: border-box; inline-size: min(34rem, 100%); background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
.help .methodology { position: absolute; z-index: 8; top: calc(100% + .35rem); right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; } h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
.periods { display: flex; align-items: center; gap: var(--issste-space-3); } .periods { display: flex; align-items: center; gap: var(--issste-space-3); }
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface); .periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; } border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
.periods button:disabled { opacity: .5; cursor: default; } .periods button:disabled { opacity: .5; cursor: default; }
// The two figures share the card in equal halves; one above the other on a narrow card. // The two figures share the card in equal halves; one above the other on a narrow card.
.conteos-head { display: flex; justify-content: flex-end; }
.help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; } .help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
.help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } .help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; } .figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; }
@@ -1,11 +1,11 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { TitleCasePipe } from '@angular/common'; import { TitleCasePipe } from '@angular/common';
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
import { filterCompatibility, GlobalApplied } from './indicadores-memory'; import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http'; import { httpMessage } from './indicadores-http';
@@ -25,10 +25,6 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
@Input({ required: true }) tema!: Tema; @Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied; @Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true; @Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
// Bumps when a metadata request finishes, including a failure that leaves metadata empty.
@Input() metadataAttempt = 0;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = ''; message = '';
periodIndex = 0; periodIndex = 0;
@@ -48,43 +44,31 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
get totalPacientes() { return this.model ? totalPacientes(this.model) : null; } get totalPacientes() { return this.model ? totalPacientes(this.model) : null; }
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); } texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); } textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
helpOpen = false; helpWhich: 'examenes' | 'pacientes' | null = null;
private helpPinned = false; private helpPinned: 'examenes' | 'pacientes' | null = null;
// True only while a metadata request is outstanding. A failure leaves metadata empty, so the next toggleHelp(which: 'examenes' | 'pacientes') {
// hover may ask again; the catalog card ignores a second ask until that request finishes. if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
private helpAsked = false; this.helpPinned = which;
// "Cómo leer": what the kit publishes for the exams' donut. Both donuts use the same categories. this.openHelp(which);
get donutGuide() {
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
} }
toggleHelp() { openHelp(which: 'examenes' | 'pacientes') {
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; } this.helpWhich = which;
this.helpPinned = true;
this.showHelp();
} }
showHelp() { hideHelp(which: 'examenes' | 'pacientes') {
this.helpOpen = true; if (this.helpPinned === which) return;
if (this.metadata || this.helpAsked) return; if (this.helpWhich === which) this.helpWhich = null;
this.helpAsked = true;
this.metadataRequested.emit();
} }
hideHelp() { if (!this.helpPinned) this.helpOpen = false; } onHelpFocusOut(which: 'examenes' | 'pacientes', event: FocusEvent) {
onHelpFocusOut(event: FocusEvent) {
const next = event.relatedTarget; const next = event.relatedTarget;
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return; if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
this.helpPinned = false; if (this.helpPinned === which) this.helpPinned = null;
this.helpOpen = false; if (this.helpWhich === which) this.helpWhich = null;
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (changes['metadata'] && this.metadata) this.helpAsked = false;
else if (changes['metadataAttempt'] && !this.metadata) this.helpAsked = false;
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]); const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
if (key !== this.key) { if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.helpAsked = false; this.clear(); this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
if (!this.visible) { this.status.set('deferred'); return; } if (!this.visible) { this.status.set('deferred'); return; }
this.load(); this.load();
} else if (this.visible && !this.loaded) this.load(); } else if (this.visible && !this.loaded) this.load();
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http'; import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format'; import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified'; import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
@@ -101,7 +101,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2' if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras') || !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) { || !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|| !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.'; this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
this.status.set('incompatible'); return; this.status.set('incompatible'); return;
} }
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p> <p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
} }
<div class="kpi-foot"> <div class="kpi-foot">
@if (temporalReference) { @if (showPeriod && temporalReference) {
<p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p> <p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
} }
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p> <p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@@ -37,9 +37,9 @@ import { MatCardModule } from '@angular/material/card';
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; } .value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; } .value span { margin-inline-start: .3em; }
// CaMa's cards are as tall as their grid row. :host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; } :host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; } :host-context(.kpi-section) .value { font-size: 1.65rem; }
`, `,
}) })
export class IndicadorKpiCard { export class IndicadorKpiCard {
@@ -47,6 +47,8 @@ export class IndicadorKpiCard {
@Input() value?: string | number | null; @Input() value?: string | number | null;
@Input() unit?: string; @Input() unit?: string;
@Input() temporalReference?: string; @Input() temporalReference?: string;
// The opportunity strip shares one period, shown by the parent instead of on every card.
@Input() showPeriod = true;
@Input() loading = false; @Input() loading = false;
@Input() notes: string[] = []; @Input() notes: string[] = [];
@Input() state = 'Pendiente de definición'; @Input() state = 'Pendiente de definición';
@@ -39,7 +39,8 @@ describe('KPI búsqueda inicial del último dato visible', () => {
latest.flush(data(periods[0], 'suppressed')); latest.flush(data(periods[0], 'suppressed'));
request(periods[1]).flush(data(periods[1])); fixture.detectChanges(); request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
expect(fixture.componentInstance.result().value).toBe(5); expect(fixture.componentInstance.result().value).toBe(5);
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1'); expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2025-S1');
expect(fixture.nativeElement.textContent).not.toContain('Último dato visible');
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.'); expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
http.expectNone(() => true); http.expectNone(() => true);
}); });
@@ -190,9 +190,11 @@ describe('KPI integración con autoridad global', () => {
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']); : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'),
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'), expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
])); ]));
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
expect(cards.filter(card => card.querySelector('.value')).every(card => card.querySelector('.kpi-state')?.classList.contains('visually-hidden'))).toBe(true);
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions. // CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false); expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
@@ -19,14 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule], imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit" template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference" [state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" /> [loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true"
[showPeriod]="false" />
@if (result().state === 'Error de consulta') { @if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button> <button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`, }`,
styles: ` styles: `
:host { display: block; min-width: 0; } :host { display: block; min-width: 0; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; } :host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; } :host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
`, `,
}) })
export class IndicadorKpiPanel implements OnChanges { export class IndicadorKpiPanel implements OnChanges {
@@ -38,7 +38,7 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); } .remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
.remove button { min-height: 44px; } .remove button { min-height: 44px; }
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); } .apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
.fields.compact { align-items: center; } .fields.compact { align-items: end; }
.fields.compact mat-form-field { flex: 0 1 14rem; } .fields.compact mat-form-field { flex: 0 1 14rem; }
.fields.compact .apply-button { margin-top: 0; } .fields.compact .apply-button { margin-top: 0; }
@media (max-width: 550px) { @media (max-width: 550px) {
@@ -0,0 +1,223 @@
// What this module covers: CaCu's compositions as the page reads them from FHIR once the Measure publishes category
// groups and the reports their crossed strata: the groups, the rows by stratum (codes, captions, explicit zeros, totals),
// the contract errors that must never become zeros, the EU7 view by follow-up status and the histopathological
// confirmation, a period without units, and that measures without groups (CaMa's) read unchanged.
// Fixtures: `fixtures/cacu_fhir_measures.json` (the Measure bundle `GET /cacu/fhir/Measure` returns with the groups
// declared) and `fixtures/cacu_fhir_reportes_estratos.json` (real `GET /cacu/fhir/MeasureReport` answers of EU7 and the
// confirmation for 2025-S2, with units, and 2021-S1, without; synthetic data of the isolated installation, N_CACU=300).
import { Bundle, resources } from './fhir';
import { categorias, datosDeReportes, gruposDeCategoria, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
import { barras, dona, modelo } from './indicadores-eu7-escenario';
import { donaConfirmacion, modeloConfirmacion } from './indicadores-confirmacion-citologia';
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
import { IndicadorDatos } from './indicadores.models';
import measuresData from './fixtures/cacu_fhir_measures.json';
import reportsData from './fixtures/cacu_fhir_reportes_estratos.json';
import camaData from './fixtures/cama_fhir_measures.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const measure = (id: string) => measures.find(m => m.id === id)!;
const answers = reportsData as unknown as Record<string, Bundle>;
const reports = (key: string) => resources(answers[key], 'MeasureReport') as Report[];
const EU7 = 'CACU-EU7', CONF = 'CACU-CONFIRMACION-CITOLOGIA';
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
type Fila = Record<string, unknown>;
const n = (filas: Fila[], estrato: string | null, categoria: string) =>
filas.filter(f => f['estrato'] === estrato && f['categoria'] === categoria).reduce((s, f) => s + (f['n'] as number), 0);
describe('Grupos de categoría publicados por la Measure', () => {
it('EU7 y la confirmación leen el grupo de cada categoría y los nombres de los grupos, en su orden', () => {
// Pins down: the optional `grupo` inside each `categoria` and the `categoria-grupo` captions reach the page as the
// EU7 and confirmation views read them; «Sin biopsia aún» keeps no group. Fails if either is dropped or reordered.
expect(Object.fromEntries(Object.entries(categorias(measure(EU7))).map(([c, v]) => [c, v.grupo]))).toEqual({
NORMAL: 'NO_ANORMAL', 'ASC-US': 'ANORMAL', LIEBG: 'ANORMAL', 'ASC-H': 'ANORMAL', LIEAG: 'ANORMAL', CIS: 'ANORMAL', SIN_DATO: 'SIN_DATO' });
expect(Object.entries(gruposDeCategoria(measure(EU7)))).toEqual([
['NO_ANORMAL', 'Sin anomalía'], ['ANORMAL', 'Anormal'], ['SIN_DATO', 'Sin dato']]);
expect(categorias(measure(CONF))['SIN_BIOPSIA'].grupo).toBeNull();
expect(gruposDeCategoria(measure(CONF))).toEqual({ NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Biopsia sin grado' });
});
it('una Measure sin grupos se lee como antes: sin grupo por categoría y sin grupos de categoría', () => {
// Pins down: groups are opt-in. CaMa's Measures declare none, so every category keeps `grupo: null` and the data
// carry no `grupos_de_categoria`. Fails if reading the new extensions changes what CaMa's views receive.
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
for (const m of cama) {
expect(Object.values(categorias(m)).every(c => c.grupo === null), m.id).toBe(true);
expect(gruposDeCategoria(m), m.id).toEqual({});
}
});
});
describe('Composiciones por estrato desde el estratificador cruzado', () => {
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre');
const porEstatus = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' });
it('cada estrato tiene una fila por categoría declarada, con su código y su etiqueta, y ceros explícitos', () => {
// Pins down: one row per (status, category), the status code as the value and its caption from the report, and a
// zero for every cell FHIR doesn't list (the report is complete). Fails if a cell goes missing or a code is replaced.
const valores = porEstatus['valores_estrato'] as string[];
expect(valores.length).toBeGreaterThan(0);
expect(porEstatus.filas.length).toBe(valores.length * Object.keys(porEstatus['categorias'] as object).length);
expect((porEstatus['etiquetas_estrato'] as Record<string, string>)['PRE_COLPOSCOPIA']).toBe('Pre colposcopia');
const listadas = (reports('eu7_2025S2')[0].group![0].stratifier as { code: unknown[]; stratum: unknown[] }[])
.find(s => s.code.length === 2 && JSON.stringify(s.code[0]).includes('estatus_seguimiento'))!.stratum.length;
expect(porEstatus.filas.filter(f => f['n'] === 0).length).toBe(porEstatus.filas.length - listadas);
expect(porEstatus.filas.every(f => f['suprimido'] === 0 && f['grupo'] === 'TOTAL')).toBe(true);
});
it('los conteos por estrato suman los de la distribución general, categoría por categoría y en total', () => {
// Pins down: the strata partition the period's units (112 patients in 2025-S2) and each category adds up across
// them; the per-stratum totals are published. Fails if the crossed stratifier is read with a shift or a loss.
const totales = porEstatus['totales_estrato'] as { n: number }[];
expect(totales.reduce((s, t) => s + t.n, 0)).toBe(112);
for (const categoria of Object.keys(general['categorias'] as object)) {
const porEstratos = (porEstatus['valores_estrato'] as string[]).reduce((s, e) => s + n(porEstatus.filas, e, categoria), 0);
expect(porEstratos, categoria).toBe(n(general.filas, null, categoria));
}
const porEdad = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'grupo_edad' });
expect((porEdad['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(112);
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['25-34']).toBe('25-34');
});
it('una celda que falta, una categoría no declarada o un estratificador ausente son errores de contrato, no ceros', () => {
// Pins down: what can't be read as a complete partition fails loudly: cells that no longer add up to the units, a
// category the Measure doesn't declare, and a period with units but without the crossed stratifier. Fails if any
// of them is silently turned into a zero.
const sinCelda = clone(reports('eu7_2025S2'));
const cruzado = sinCelda[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as { stratum: unknown[] };
cruzado.stratum.shift();
expect(() => datosDeReportes(measure(EU7), sinCelda, 'semestre', { estrato: 'estatus_seguimiento' }))
.toThrowError('Los conteos por estrato no suman las unidades del periodo');
const ajena = clone(reports('eu7_2025S2'));
const celda = (ajena[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as
{ stratum: { component: { value: { coding: { code: string }[] } }[] }[] }).stratum[0];
celda.component[1].value.coding[0].code = 'GLANDULAR';
expect(() => datosDeReportes(measure(EU7), ajena, 'semestre', { estrato: 'estatus_seguimiento' }))
.toThrowError('Categoría no declarada en el estrato');
const sinCruce = clone(reports('eu7_2025S2'));
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
expect(() => datosDeReportes(measure(EU7), sinCruce, 'semestre', { estrato: 'estatus_seguimiento' }))
.toThrowError('Dimensión no admitida');
});
it('un periodo sin unidades no tiene filas por estrato y no es un error', () => {
// Pins down: 2021-S1 has no patients; its report has nothing to cross, so the stratified data carry the period but
// no rows, and the general distribution is all zeros. Fails if an empty period is read as an error or as data.
const vacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' });
expect(vacio.periodos).toEqual(['2021-S1']);
expect(vacio.filas).toEqual([]);
const generalVacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre');
expect(generalVacio.filas.every(f => f['n'] === 0)).toBe(true);
});
});
describe('Vistas propias de CaCu con los datos de FHIR', () => {
it('EU7: el modelo por escenario se construye y la dona y las barras tienen datos', () => {
// Pins down: with the groups and the rows by follow-up status, EU7's coordinated view builds its model (112
// patients in groups Anormal / Sin anomalía, «Sin dato» apart) and both figures have traces. Fails if the view
// falls back to «incompatible» with the data FHIR publishes.
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
const m = modelo(general, escenarios, '2025-S2');
expect(m.vacio).toBe(false);
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Sin anomalía', 'Anormal']);
expect(m.escenarios.map(e => e.etiqueta)).toContain('Pre colposcopia');
expect(dona(m, {}, 'claro').data.length).toBeGreaterThan(0);
expect(barras(m, {}, 'claro').data.length).toBeGreaterThan(0);
});
it('EU7: el texto emergente de cada sector de la dona nombra la categoría, los pacientes y el porcentaje', () => {
// Pins down: both rings carry one pre-formatted hover text per sector («2 pacientes, 2.1 % del total con
// resultado» for LIEAG, 2 of the 95 patients with a result) and their template reads it by name. A pie wraps
// `customdata` in an extra array, so a template that indexes it printed «2,2.1 pacientes, - %». Fails if the
// template goes back to indexing `customdata` or a sector loses its text.
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
const m = modelo(general, escenarios, '2025-S2');
const anillos = dona(m, {}, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
expect(anillos.length).toBe(2);
for (const anillo of anillos) {
expect(anillo['hovertemplate']).not.toContain('customdata');
expect(anillo['hovertemplate']).toContain('%{hovertext}');
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
}
const exterior = anillos.find(t => t['name'] === 'categorias')!;
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
expect(m.total).toBe(95);
expect(textos[etiquetas.indexOf('LIEAG')]).toBe('2 pacientes, 2.1 % del total con resultado');
expect(textos.every(t => /^\d+ pacientes, \d+(\.\d)? % del total con resultado$/.test(t))).toBe(true);
});
it('EU7: un periodo sin pacientes es un periodo vacío, no una respuesta incompatible', () => {
// Pins down: for 2021-S1 FHIR publishes the general distribution as explicit zeros and no scenario; the view reads
// it as empty. A positive count without scenarios is still rejected. Fails if an empty period shows
// «incompatible», or if a real mismatch is hidden as empty.
const general = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
const m = modelo(general, escenarios, '2021-S1');
expect(m.vacio).toBe(true);
expect(m.escenarios).toEqual([]);
const conPacientes = clone(general);
conPacientes.filas[0]['n'] = 3;
expect(() => modelo(conPacientes, escenarios, '2021-S1')).toThrow(/No hay escenarios que correspondan/);
});
it('EU7: el mismo reporte servido en dos respuestas es una sola procedencia aunque cambie la hora de la respuesta', () => {
// Pins down: the view asks for the general and the stratified data in two requests; the WebApi serves the same
// stored report (same id and cut-off) with each response's own `date`. That is one provenance; without report ids,
// a different generation time still means different reports. Fails if the view rejects FHIR's two responses of one
// report, or accepts two anonymous answers generated apart.
const segunda = clone(reports('eu7_2025S2'));
segunda[0].date = '2099-01-01T00:00:00Z';
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), segunda, 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
expect(modelo(general, escenarios, '2025-S2').vacio).toBe(false);
const anonimo = (d: IndicadorDatos) => ({ ...d, reportes: (d['reportes'] as Fila[]).map(r => ({ ...r, report_id: null })) }) as IndicadorDatos;
expect(() => modelo(anonimo(general), anonimo(escenarios), '2025-S2')).toThrow(/reportes distintos/);
});
it('confirmación: la tabla por citología y los dos grupos de grados se construyen', () => {
// Pins down: the confirmation by cytology result builds its table from the crossed stratifier (6 patients in
// 2025-S2), with its two groups and LIEAG's as the base view, and «Sin biopsia aún» / «Biopsia sin grado»
// apart. Fails if the view can't read FHIR's groups or strata.
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
const m = modeloConfirmacion(datos, '2025-S2');
expect(m.vacio).toBe(false);
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Menor que LIEAG', 'LIEAG o más']);
expect(m.base).toBe('ANORMAL');
expect(m.aparte.map(a => a.id).sort()).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
expect((datos['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(6);
});
it('confirmación: el texto emergente de cada sector de la dona nombra el grado, las mujeres con biopsia y el porcentaje', () => {
// Pins down: both rings carry one pre-formatted hover text per sector («3 mujeres con biopsia, 75.0 %» for the
// grades LIEAG o más… of the 4 women with a biopsy in 2025-S2) and their template reads it by name, because a pie
// wraps `customdata` in an extra array and indexing it printed «3,75.0 % mujeres con biopsia, -». Fails if the
// template goes back to indexing `customdata` or a sector loses its text.
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
const m = modeloConfirmacion(datos, '2025-S2');
const anillos = donaConfirmacion(m, { grupo: m.base }, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
expect(anillos.length).toBe(2);
for (const anillo of anillos) {
expect(anillo['hovertemplate']).not.toContain('customdata');
expect(anillo['hovertemplate']).toContain('%{hovertext}');
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
}
const exterior = anillos.find(t => t['name'] === 'categorias')!;
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
expect(textos[etiquetas.indexOf('LIEAG (CIN 2 y 3)')]).toBe('3 mujeres con biopsia, 75.0 %');
expect(textos.every(t => /^\d+ mujeres con biopsia, \d+(\.\d)? %$/.test(t))).toBe(true);
});
it('la compuerta de EU7 usa los estratos que declara la Measure y no activa filtros para otras composiciones', () => {
// Pins down: EU7 declares `estatus_seguimiento`, so its view opens without local filters; the stratified
// capabilities of the generic figure panel stay empty for every CaCu and CaMa measure. Fails if the gate is lost
// or if filters appear for compositions that never had them.
const eu7 = indicadorDeMeasure(measure(EU7));
expect(declaraEstrato(eu7, 'estatus_seguimiento')).toBe(true);
expect(declaraEstrato(indicadorDeMeasure(measure(CONF)), 'estatus_seguimiento')).toBe(false);
expect(declaraEstrato(indicadorDeMeasure(measure('CACU-EU13')), 'estatus_seguimiento')).toBe(false);
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
for (const item of [...measures, ...cama].map(indicadorDeMeasure)) expect(stratifiedCapabilities(item), item.id).toEqual([]);
});
});
@@ -0,0 +1,133 @@
// What this module covers: how CaCu's FHIR measures reach the indicator page: the page's id of each measure, and what the
// initial-period anchor (`cacu_eu7`) makes of a C2 Measure that publishes, or does not publish, its category labels.
// The Measure and the report are synthetic and minimal: the shape of `GET /cacu/fhir/Measure` and `/MeasureReport`.
import { Bundle, resources } from './fhir';
import { Measure, Report, datosDeReportes, indicadorDeMeasure, indicadorId } from './indicadores-fhir';
import { c2Figure } from './indicadores-c2-adapter';
import { FigureSelection } from './indicadores.models';
import measuresData from './fixtures/cacu_fhir_measures.json';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
'CACU-RIESGO-BANDA', 'IND1'];
const etiqueta = (codigo: string, texto: string, color: string) => ({ url: `${STRUCTURE}/categoria`, extension: [
{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: texto }, { url: 'color', valueString: color }] });
const eu7 = (extra: object[]): Measure => ({
resourceType: 'Measure', id: 'CACU-EU7', version: '0.3.3', title: 'Distribución de resultados citológicos',
subjectCodeableConcept: { coding: [{ code: 'paciente' }] },
extension: [{ url: `${STRUCTURE}/contrato`, valueCode: 'C2' }, { url: `${STRUCTURE}/tipos-periodo`, valueCode: 'semestre' }, ...extra],
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [], stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [] }] }],
} as unknown as Measure);
const reporte = (): Report => ({
resourceType: 'MeasureReport', id: 'CACU-EU7-1', period: { start: '2025-07-01', end: '2025-12-31' },
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 12 }],
stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [
{ value: { coding: [{ code: 'NORMAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 8 }] },
{ value: { coding: [{ code: 'ASC-US' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 3 }] },
{ value: { coding: [{ code: 'SIN_DATO' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 1 }] },
] }] }],
} as unknown as Report);
const aplicado: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 };
const ancla = KPI_BY_DOMAIN.cacu[0];
describe('Identificadores de CaCu entre FHIR y la página', () => {
it('cada medida que publica el WebApi tiene el id de minúsculas que usa la página y ninguno se repite', () => {
// Pins down: the table covers the seven measures `GET /cacu/fhir/Measure` lists and the ids are unique. Fails if a
// measure is published without a correspondence (it would come back as `CACU_X`, which no card matches) or two
// measures collapse into one page id.
const ids = ENDPOINT.map(indicadorId);
expect(ids.sort()).toEqual(['cacu_confirmacion_citologia', 'cacu_dias_toma_diagnostico', 'cacu_eu13', 'cacu_eu7',
'cacu_eu_tiempo_reporte', 'cacu_riesgo_banda', 'ind1']);
expect(ENDPOINT.every(id => Object.hasOwn(CACU_MEASURE_IDS, id))).toBe(true);
});
it('los ids que la página busca (ancla, tiempos, confirmación) existen entre los publicados', () => {
// Pins down: the page's own constants (the KPI definitions of CaCu, the confirmation card's id and the result-time KPI)
// are values of the table. Fails if the page renames one of them without the table: the catalog would keep `CACU_EU7`
// while the page looks for `cacu_eu7`, and no initial period would be searched.
const publicados = Object.values(CACU_MEASURE_IDS);
for (const id of [...KPI_BY_DOMAIN.cacu.map(k => k.id), CACU_RESULTADO_KPI.id, ID_CONFIRMACION, 'cacu_eu7']) {
expect(publicados).toContain(id);
}
});
it('el catálogo de una medida de CaCu lleva el id de la página y sus figuras', () => {
// Pins down: the catalog entry takes the page id and the `figuras` the Measure publishes. Fails if the mapper stops
// using the CaCu table or drops the figures.
const item = indicadorDeMeasure(eu7([{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_donas' },
{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_barras' }]));
expect(item.id).toBe('cacu_eu7');
expect(item.figuras).toEqual(['fig_c2_donas', 'fig_c2_barras']);
});
});
describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => {
it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => {
// Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum
// (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's
// categories or the anchor no longer accepts a CaCu partition.
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('ASC-US', 'ASC-US', '#2F6DB3'),
etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
const datos = datosDeReportes(measure, [reporte()], 'semestre');
expect(datos.filas.map(f => [f['categoria'], f['n']])).toEqual([['NORMAL', 8], ['ASC-US', 3], ['SIN_DATO', 1]]);
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
expect(resultado.state).toBe('Disponible');
expect(resultado.value).toBe(12);
});
it('sin etiquetas, el mismo reporte no deja filas y el ancla no encuentra periodo', () => {
// Pins down the failure the Measure without `categoria` causes: the report counts 12 patients, but with no declared
// category there is no row, so the anchor reads «Sin filas utilizables» and the initial period stays empty. Fails
// if the page starts inventing categories from the report (it must keep asking the Measure).
const datos = datosDeReportes(eu7([]), [reporte()], 'semestre');
expect(datos.filas).toEqual([]);
expect(kpiResult(datos, ancla, 'cacu', aplicado).state).toBe('Sin filas utilizables');
});
});
// `fixtures/cacu_fhir_measures.json` is the Measure bundle `GET /cacu/fhir/Measure` returns from the dbt definitions once
// CaCu declares its figures and category labels (WebApi with the figures and labels declared in Transformation); the reports are built
// from the categories each Measure declares, as the WebApi would count them.
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const medida = (id: string) => publicadas.find(m => m.id === id)!;
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
const codigo = (c: string) => ({ coding: [{ code: c }] });
const reporteDe = (m: Measure, conteos: number[]): Report => ({
resourceType: 'MeasureReport', id: `${m.id}-1`, period: { start: '2025-07-01', end: '2025-12-31' },
group: [{ code: codigo('TOTAL'), population: [{ code: codigo('initial-population'), count: conteos.reduce((a, b) => a + b, 0) }],
stratifier: [{ code: [codigo('categoria')], stratum: declaradas(m).map((c, i) => ({
value: codigo(c), population: [{ code: codigo('initial-population'), count: conteos[i] }] })) }] }],
} as unknown as 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
// 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_riesgo_banda: [], ind1: [],
});
});
it('con las etiquetas publicadas, el ancla muestra el total y el donut y las barras se dibujan', () => {
// Pins down the whole chain for the anchor: published categories -> rows -> «Pacientes evaluadas» total (16) ->
// supported C2 donut and bars. Fails if the page cannot read what the WebApi publishes for CaCu's distribution.
const eu7 = medida('CACU-EU7');
const datos = datosDeReportes(eu7, [reporteDe(eu7, [8, 3, 2, 1, 1, 0, 1])], 'semestre');
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
expect(resultado).toMatchObject({ state: 'Disponible', value: 16 });
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
const dibujo = c2Figure(datos, { dominio: 'cacu', indicador: 'cacu_eu7', figura, tipoPeriodo: 'semestre', tema: 'claro',
periodos: ['2025-S2'] } as unknown as FigureSelection);
expect(dibujo.status).toBe('supported');
}
});
});
@@ -0,0 +1,15 @@
// How CaCu's FHIR measures map onto what the indicator page reads: the page's id of each measure.
//
// The WebApi names a measure `CACU-EU7`, `CACU-CONFIRMACION-CITOLOGIA` or `IND1`; the page, its KPI definitions, the
// initial-period anchor and the cards that have a view of their own (`cacu_eu7`, `cacu_confirmacion_citologia`, the
// time pair) all use the lower-case ids below. The generic rule would give `CACU_EU7`, which none of them matches, so
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
'CACU-EU13': 'cacu_eu13',
'CACU-EU7': 'cacu_eu7',
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
'IND1': 'ind1',
};
@@ -101,12 +101,12 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id)); expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
expect(before[0].indicador.id).toBe('cacu_eu7'); expect(before[0].indicador.id).toBe('cacu_eu7');
page.togglePinned(original[0]); fixture.detectChanges(); page.togglePinned(original[0]); fixture.detectChanges();
expect(cards()[0]).toBe(card('cacu_eu13')); expect(cards()[0]).toBe(card('cacu_eu7'));
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges(); page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']); expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id)); for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
page.showAllIndicators(); fixture.detectChanges(); page.showAllIndicators(); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('cacu_eu13'); expect(cards()[0].indicador.id).toBe('cacu_eu7');
expect(page.catalog()).toBe(original); expect(page.catalog()).toBe(original);
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true); expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
http.expectNone(() => true); http.expectNone(() => true);
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => { it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator. // Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied)) expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con resultado maligno.' }); .toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
}); });
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => { it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied); const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -113,9 +113,10 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
const respuestas: Record<string, unknown> = visibles const respuestas: Record<string, unknown> = {
? { cama_tasa_deteccion_histopatologica: tasaVisible, cama_dias_resultado_diagnostico: diasVisible, cama_histopatologia_birads: generalFixture } cama_dias_resultado_diagnostico: visibles ? diasVisible : diasSuprimido,
: { cama_tasa_deteccion_histopatologica: tasaSuprimida, cama_dias_resultado_diagnostico: diasSuprimido, cama_histopatologia_birads: generalFixture }; cama_histopatologia_birads: generalFixture,
};
const pedidos: string[] = []; const pedidos: string[] = [];
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) { for (const r of ola) {
@@ -132,28 +133,29 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[]; const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
it('los tres indicadores publicados se piden y se dibujan; los cinco restantes de la lista siguen pendientes', () => { it('omite el panel y las consultas de detección aunque la medida figure en el catálogo', () => {
const pedidos = montar(true); const pedidos = montar(true);
expect(REALES.map(i => i.id)).toContain('cama_tasa_deteccion_histopatologica');
expect(pedidos.some(p => p.includes('cama_tasa_deteccion_histopatologica'))).toBe(false);
expect(pedidos.filter(p => p.includes('/datos'))).toEqual([ expect(pedidos.filter(p => p.includes('/datos'))).toEqual([
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1', '/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1', '/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']); const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
expect(titulos.filter(([t]) => ['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!))) expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]); expect(titulos.filter(([, estado]) => estado === 'dibujado'))
expect(graficas()).toHaveLength(3); .toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]);
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]); expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]);
}); });
it('con el umbral normal los dos paneles C1 y C3r avisan el periodo suprimido, y la matriz CAM-03 sigue visible', () => { it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => {
montar(false); montar(false);
const texto = paneles().map(p => p.textContent!); const texto = paneles().map(p => p.textContent!);
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2); expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(1);
expect(graficas()).toHaveLength(3); expect(graficas()).toHaveLength(2);
}); });
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => { it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
montar(false); montar(false);
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[]; const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
expect(notas).toHaveLength(2); expect(notas).toHaveLength(1);
for (const nota of notas) { for (const nota of notas) {
expect(nota.open).toBe(false); expect(nota.open).toBe(false);
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos'); expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
@@ -161,7 +163,6 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
} }
notas[0].open = true; notas[0].open = true;
expect(notas[0].open).toBe(true); expect(notas[0].open).toBe(true);
expect(notas[1].open).toBe(false);
}); });
}); });
@@ -204,10 +205,12 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => { it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
// Fails if the unavailable slot displays a value or displaces the published measures. // Fails if the unavailable slot displays a value or displaces the published measures.
cargar(completo()); const pedidos = cargar(completo());
expect(kpis()).toHaveLength(5); expect(kpis()).toHaveLength(5);
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente'); expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.'); expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.'); expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible'); expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
expect(kpis()[4].querySelector('.value')).toBeNull(); expect(kpis()[4].querySelector('.value')).toBeNull();
@@ -50,10 +50,10 @@ describe('Identificadores de CaMa entre FHIR y la página', () => {
}); });
it('el id de una medida de otro dominio sigue la regla general', () => { it('el id de una medida de otro dominio sigue la regla general', () => {
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures // Pins down: only CaMa's table maps CaMa's measures, and TEA's keep `-` to `_` (CaCu has a table of its own, see
// ids of other domains or the generic rule changes. // indicadores-cacu-fhir.spec.ts). Fails if CaMa's table captures ids of other domains or the generic rule changes.
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg'); expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7'); expect(Object.hasOwn(CAMA_MEASURE_IDS, 'CACU-EU7')).toBe(false);
}); });
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => { it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
@@ -308,3 +308,33 @@ describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () =>
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]); expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
}); });
}); });
describe('Conteos publicados de CaMa en la ruta FHIR', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
function pedir(id: string, fhirId: string) {
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).datos('cama', id, 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
return answer;
}
it('las mastografías llegan a la tarjeta con los conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA');
expect(mostrado.filas).toEqual(publicado.filas);
const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
});
it('los pacientes conservan sus conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
expect(pacientes.filas).toEqual(publicado.filas);
});
});
@@ -73,7 +73,7 @@ describe('Tasa de detección histopatológica (C1)', () => {
expect(d['grupos']).toEqual({ total: 'Total' }); expect(d['grupos']).toEqual({ total: 'Total' });
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]); expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({ expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` }); state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con riesgo a carcinoma.` });
}); });
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => { it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'], ['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
]); ]);
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([ expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']); 'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]); expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
}); });
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => { it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => { it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia"). // Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con resultado maligno.' }); expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
}); });
it('una tasa de cero con denominador es un cero real, no una ausencia', () => { it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -213,8 +213,10 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) }); const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort()); expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad'); expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
expect(cards().map(card => text(card, 'h3'))).toEqual([ expect(cards().map(card => text(card, 'h3'))).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica',
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']); 'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]); expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([ expect(cards().map(card => text(card, '.kpi-state'))).toEqual([
@@ -234,7 +236,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible'); expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible');
expect(text(cards()[4], '.value')).toBeUndefined(); expect(text(cards()[4], '.value')).toBeUndefined();
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false); expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.'); expect(cards()[1].textContent).toContain('2 de 5 biopsias con riesgo a carcinoma.');
}); });
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => { it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
@@ -254,7 +256,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined(); expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
expect(text(cards()[0], '.value')).toBe('5pacientes'); expect(text(cards()[0], '.value')).toBe('5pacientes');
expect(fixture.nativeElement.textContent).not.toContain('private'); expect(fixture.nativeElement.textContent).not.toContain('private');
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía interpretación radiológica"]')).not.toBeNull(); expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía a interpretación radiológica"]')).not.toBeNull();
}); });
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => { it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators. // Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
@@ -1,5 +1,5 @@
// Covers the clinical section of CaMa's summary: its heading and counter, and the controls the mockup does not // Covers the clinical section: its heading, and the controls the mockup does not have
// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep. // (search, pins, floating navigation, representation selector, figure count) in every domain.
// Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view). // Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view).
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
@@ -13,7 +13,7 @@ const item = (id: string, titulo: string, contrato: string, figuras: string[]) =
// The catalog 18080 publishes for CaMa. // The catalog 18080 publishes for CaMa.
const CAMA = [ const CAMA = [
item('cama_biopsias', 'Distribución de resultados de biopsia', 'C2', ['fig_c2_donas', 'fig_c2_barras']), item('cama_biopsias', 'Distribución de resultados de biopsia', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']), item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']), item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']), item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']),
item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']), item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
@@ -53,8 +53,10 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
expect(titles()).not.toContain('Distribución de resultados de biopsia'); expect(titles()).not.toContain('Distribución de resultados de biopsia');
// The patients' counts go on the exams' card, so the partner indicator has no card of its own. // The patients' counts go on the exams' card, so the partner indicator has no card of its own.
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6'); expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
// Only the paired card is a published indicator the summary draws; the other three are in Histórico. // The paired card has no card title; each donut names itself. The other three indicators are in Histórico.
expect(titles()).toEqual(['Porcentaje de mastografías']); expect(titles()).toEqual([]);
expect(root().querySelector('app-indicador-conteos-pareados')).not.toBeNull();
expect(section().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
expect(root().textContent).not.toContain('indicador publicado'); expect(root().textContent).not.toContain('indicador publicado');
}); });
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => { it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
@@ -65,6 +67,12 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo); expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
} }
}); });
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).not.toContain(CAMA[1].titulo);
});
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => { it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
open('cama', CAMA); open('cama', CAMA);
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement; const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
@@ -105,18 +113,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges(); fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
expect(titles()).toEqual(before); expect(titles()).toEqual(before);
}); });
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => { it.each(['tea', 'cacu'] as const)('%s usa el mismo resumen clínico que CaMa: sin buscador, fijados ni conteo de figuras', domain => {
// Fails if CaMa's simplified section leaks into the other domains.
open(domain, OTRO(domain)); open(domain, OTRO(domain));
expect(root().querySelector('.catalog-search')).not.toBeNull(); expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
expect(root().querySelectorAll('.pin-toggle').length).toBe(6); expect(root().querySelector('#dashboard-title')?.textContent?.trim()).toBe(domain === 'tea' ? 'Trastorno del espectro autista' : 'Cáncer cervicouterino');
expect(section().textContent).toContain('2 figuras publicadas'); expect(root().querySelector('header .domain')).toBeNull();
expect(root().querySelector('.catalog-search')).toBeNull();
expect(root().querySelector('.pin-toggle')).toBeNull();
expect(section().textContent).not.toContain('figuras publicadas');
expect(root().textContent).not.toContain('indicadores publicados'); expect(root().textContent).not.toContain('indicadores publicados');
}); });
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
open('cacu', OTRO('cacu'));
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
open('tea', OTRO('tea'));
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores gráficos');
});
}); });
@@ -33,8 +33,7 @@ describe('Cambio de dominio con consultas pendientes', () => {
fixture.detectChanges(); fixture.detectChanges();
expect(text()).not.toContain('Indicador de CaMa'); expect(text()).not.toContain('Indicador de CaMa');
}); });
it('los controles propios de cada dominio se conservan al ir y volver', () => { it('el resumen clínico es el mismo al ir y volver, y el catálogo no se mezcla', () => {
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
const abrir = (d: 'cacu' | 'cama', n: number) => { const abrir = (d: 'cacu' | 'cama', n: number) => {
fixture.componentInstance.changeDominio(d); fixture.detectChanges(); fixture.componentInstance.changeDominio(d); fixture.detectChanges();
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges(); http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
@@ -42,8 +41,9 @@ describe('Cambio de dominio con consultas pendientes', () => {
}; };
const el = () => fixture.nativeElement as HTMLElement; const el = () => fixture.nativeElement as HTMLElement;
abrir('cacu', 6); abrir('cacu', 6);
expect(el().querySelector('.catalog-search')).not.toBeNull(); expect(el().querySelector('.catalog-search')).toBeNull();
expect(el().querySelectorAll('.pin-toggle').length).toBe(6); expect(el().querySelector('.pin-toggle')).toBeNull();
expect(el().querySelector('#dashboard-title')?.textContent?.trim()).toBe('Cáncer cervicouterino');
expect(el().textContent).toContain('Intervalo de análisis'); expect(el().textContent).toContain('Intervalo de análisis');
abrir('cama', 6); abrir('cama', 6);
expect(el().querySelector('.catalog-search')).toBeNull(); expect(el().querySelector('.catalog-search')).toBeNull();
@@ -51,9 +51,8 @@ describe('Cambio de dominio con consultas pendientes', () => {
expect(el().textContent).not.toContain('Buscar indicadores'); expect(el().textContent).not.toContain('Buscar indicadores');
expect(el().textContent).not.toContain('cacu_'); expect(el().textContent).not.toContain('cacu_');
abrir('cacu', 6); abrir('cacu', 6);
// On the way back the page state (not only the DOM) says CaCu has its search again.
expect(fixture.componentInstance.dominio).toBe('cacu'); expect(fixture.componentInstance.dominio).toBe('cacu');
expect(fixture.componentInstance.searchVisible()).toBe(true); expect(fixture.componentInstance.searchVisible()).toBe(false);
expect(el().textContent).toContain('Intervalo de análisis'); expect(el().textContent).toContain('Intervalo de análisis');
expect(el().textContent).not.toContain('cama_'); expect(el().textContent).not.toContain('cama_');
}); });
@@ -228,17 +228,18 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0)); const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
const exterior = m.grados.map(g => m.totales[g.id]!); const exterior = m.grados.map(g => m.totales[g.id]!);
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' }; // A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]); const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
const hoverText = (values: number[]) => values.map(n => `${miles(n)} mujeres con biopsia, ${shareText(n, total)}`);
return { data: [ return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside', { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text }, text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' }, marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } }, marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior), labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior),
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } }, marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } }; config: { displayModeBar: false } };
@@ -126,6 +126,7 @@ describe('Conteos pareados de CaMa: lo que no se calcula', () => {
const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record<string, unknown> }; const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record<string, unknown> };
expect(barras.layout['annotations']).toBeUndefined(); expect(barras.layout['annotations']).toBeUndefined();
expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i); expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i);
expect(JSON.stringify(barras)).toContain('pacientes (su categoría más alta)');
expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']); expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']);
}); });
it.each([ it.each([
@@ -155,7 +156,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController; let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] }); const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
const CATALOGO = [ const CATALOGO = [
item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']), item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']), item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']), item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']),
]; ];
@@ -202,23 +203,53 @@ describe('Tarjeta pareada de CaMa en la página', () => {
// Fails if the patients' indicator keeps a card of its own beside the pair. // Fails if the patients' indicator keeps a card of its own beside the pair.
const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary. // Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
expect(titulos).toEqual(['Porcentaje de mastografías']); // The pair has no card title; each donut has its own heading.
expect(titulos).toEqual([]);
expect(root().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
expect(root().textContent).not.toContain('indicador publicado'); expect(root().textContent).not.toContain('indicador publicado');
}); });
it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => { it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => {
abrir(); abrir();
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim(); const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim()); const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
expect(h3).toEqual(['Mastografías por categoría, 2025-S2', 'Pacientes por categoría, 2025-S2']); expect(h3).toEqual([
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 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');
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
expect(graficas).toHaveLength(2); expect(graficas).toHaveLength(2);
expect(graficas.map(g => g.label)).toEqual(h3);
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]); expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]);
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]); expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
expect(root().querySelector('.published-values caption')?.textContent).toContain('su categoría más alta');
expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente'); expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente');
expect(root().querySelector('.help-icon')?.getAttribute('aria-label')).toBe('Cómo leer'); expect([...root().querySelectorAll('.help-icon')].map(b => b.getAttribute('aria-label'))).toEqual(['Cómo leer, mastografías por categoría', 'Cómo leer, pacientes por categoría']);
expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato'); expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato');
}); });
it('cada ayuda muestra su explicación exacta sin depender de metadatos de FHIR', () => {
abrir();
const [mastografias, pacientes] = [...root().querySelectorAll<HTMLButtonElement>('.help-icon')];
const ayuda = () => root().querySelector('[role=tooltip]');
mastografias.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
fixture.detectChanges();
expect(ayuda()?.textContent?.trim()).toBe('Cada mastografía cuenta en su propia categoría.');
expect(mastografias.getAttribute('aria-describedby')).toBe(ayuda()?.id);
pacientes.click();
fixture.detectChanges();
expect(ayuda()?.textContent?.trim()).toBe('La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.');
expect(pacientes.getAttribute('aria-describedby')).toBe(ayuda()?.id);
expect(mastografias.getAttribute('aria-expanded')).toBe('false');
expect(root().querySelectorAll('[role=tooltip]')).toHaveLength(1);
pacientes.click();
fixture.detectChanges();
expect(ayuda()).toBeNull();
http.expectNone(r => r.url.endsWith('/metadatos'));
});
it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => { it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => {
abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })); abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' }));
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
@@ -248,45 +279,3 @@ describe('Tarjeta pareada de CaMa en la página', () => {
expect(pedidos().length).toBeGreaterThan(0); expect(pedidos().length).toBeGreaterThan(0);
}); });
}); });
describe('Cómo leer de conteos pareados: reintento tras un fallo', () => {
it('vuelve a pedir los metadatos después de un fallo, sin duplicar la consulta abierta ni la ya recibida', () => {
TestBed.overrideComponent(IndicadorConteosPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
const fixture = TestBed.createComponent(IndicadorCatalogCard);
const http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama');
fixture.componentRef.setInput('indicador', {
id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías', contrato: 'C2',
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'],
});
fixture.componentRef.setInput('tema', 'claro');
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 });
fixture.detectChanges();
fixture.componentInstance.setVisible(true);
fixture.detectChanges();
const conteos = fixture.debugElement.query(By.directive(IndicadorConteosPareados)).componentInstance as IndicadorConteosPareados;
const meta = () => http.match(r => r.url.endsWith('/metadatos'));
conteos.showHelp();
fixture.detectChanges();
const primero = meta();
expect(primero).toHaveLength(1);
conteos.showHelp();
fixture.detectChanges();
expect(meta()).toHaveLength(0);
primero[0].flush('no', { status: 500, statusText: 'Error' });
fixture.detectChanges();
conteos.showHelp();
fixture.detectChanges();
const segundo = meta();
expect(segundo).toHaveLength(1);
segundo[0].flush({ descripcion: 'Lectura de la dona' });
fixture.detectChanges();
conteos.showHelp();
fixture.detectChanges();
expect(meta()).toHaveLength(0);
fixture.destroy();
http.match(() => true);
http.verify();
});
});
@@ -183,7 +183,7 @@ export function donaPacientes(m: ModeloConteos, par: ParConteos, tema: Tema, anc
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */ /** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure { export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta)); const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
const nombres = { pacientes: `${par.unidades.pacientes} (su categoría más grave)`, examenes: par.unidades.examenes }; const nombres = { pacientes: `${par.unidades.pacientes} (su categoría más alta)`, examenes: par.unidades.examenes };
const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') => const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') =>
v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato'; v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato';
const traza = (clave: 'pacientes' | 'examenes', color: string) => ({ const traza = (clave: 'pacientes' | 'examenes', color: string) => ({
@@ -19,7 +19,9 @@ export class IndicadoresDefinitions {
@Input() loading = false; @Input() loading = false;
@Input() error = ''; @Input() error = '';
readonly retry = output<void>(); readonly retry = output<void>();
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' }; readonly domainNames: Record<Dominio, string> = {
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
};
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' }; readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
readonly figureDisplayName = figureDisplayName; readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION; readonly periodInterpretation = PERIOD_INTERPRETATION;
@@ -119,8 +119,12 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
return active[0]; return active[0];
}; };
const rg = reporte(general), re = reporte(porEscenario); const rg = reporte(general), re = reporte(porEscenario);
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha'] // With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.'); // `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there.
// Without ids, the generation time is still part of the provenance.
const identificados = rg?.['report_id'] != null && re?.['report_id'] != null;
const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha'];
if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.'); if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
// Missing rows remain unavailable. Catalog order is used only for the accessible // Missing rows remain unavailable. Catalog order is used only for the accessible
// list of missing categories; a partial distribution is never drawn as a donut. // list of missing categories; a partial distribution is never drawn as a donut.
@@ -145,17 +149,20 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario, return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null }; den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
}); });
// A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no
// scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one.
const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0);
// Compare only fully published sums. Never derive a hidden value by subtraction. // Compare only fully published sums. Never derive a hidden value by subtraction.
if (escenarios.length) { if (escenarios.length) {
for (const c of cats) { for (const c of cats) {
const total = suma(escenarios.map(s => s.celdas[c.id])); const total = suma(escenarios.map(s => s.celdas[c.id]));
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.'); if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
} }
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.'); } else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.');
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.'); if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO], return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta, sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size, total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] }; notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
} }
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo); const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
@@ -193,19 +200,20 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
}; };
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text', const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' }; insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' }; // A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]); const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
const hoverText = (values: number[]) => values.map(n => `${miles(n)} pacientes, ${percentNumber(100 * n / m.total!)} % del total con resultado`);
return { data: [ return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text }, text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' }, marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false), labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
textfont: { color: '#FFFFFF' }, customdata: custom(interior), textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true), labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
textfont: { size: 11 }, customdata: custom(exterior), textfont: { size: 11 }, hovertext: hoverText(exterior),
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, ], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } }; config: { displayModeBar: false } };
File diff suppressed because one or more lines are too long
@@ -2,12 +2,14 @@
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the // technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into // C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
// the shapes the page reads and passed through the same checks. // the shapes the page reads and passed through the same checks.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database. // Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
// in the shape `webapi/fhir/tea.py` emits them.
import { TestBed } from '@angular/core/testing'; import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir'; import { Bundle, Resource, resources } from './fhir';
import { import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado, cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
periodosDesde, Report, periodosDesde, Report,
@@ -20,6 +22,49 @@ import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-f
import { IndicadorDatos } from './indicadores.models'; import { IndicadorDatos } from './indicadores.models';
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure; const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
const CURVA = `${SD}/curva-referencia`;
const curva = {
url: CURVA, extension: [
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
],
};
const prediccion = (zona: string, z: number | null) => ({
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', 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' },
...(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 },
],
});
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
function conModelo(): Bundle {
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
for (const r of resources(bundle)) {
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
r.extension = [...(r.extension ?? []), curva];
}
const riesgo: Resource = {
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
meta: { tag: resources(bundle)[0].meta?.tag },
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
};
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
return bundle;
}
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[]; const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
describe('Indicadores sobre FHIR', () => { describe('Indicadores sobre FHIR', () => {
@@ -173,14 +218,15 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 }); expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12, expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] }); css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 }); expect(response.resumen_eeg).toMatchObject({ validadas: true, con_eeg_valido: 3, normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior'); expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
}); });
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => { it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each // Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if // the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
// the summary stops passing the page's checks or a map appears for a metric without electrodes. // and median from the code system and its observation, and one map per evaluable metric from its electrodes'
// z-scores. Fails if the summary stops passing the page's checks or a map appears for a metric without electrodes.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4')); const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente); http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg); http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
@@ -188,13 +234,70 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(detalle.grupo_edad).toBe('16-23 meses'); expect(detalle.grupo_edad).toBe('16-23 meses');
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' }); expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
expect(detalle.eeg!.calidad).toBe('bueno'); expect(detalle.eeg!.calidad).toBe('bueno');
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' }); expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'line-noise')).toMatchObject({ valor: 3.5, unidad: 'dB', nivel: 'bueno', decisivo: false, electrodo: null });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'clean-windows')).toMatchObject({ valor: 95, decisivo: true });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'triage-level')?.valor).toBe('completo');
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!; const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 }); expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08, referencia: { min: 4.5, max: 7, mediana: 5.75 }, sin_evaluar: null });
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.'); expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']); expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
}); });
it('el mapa de electrodos del reporte no da una segunda tarjeta a su métrica', async () => {
// Pins down: the report's result lists each metric's observation and its electrode-map one, both coded under the
// metric's code, and only the metric observation becomes a card. Fails if the alteraciones filter stops skipping
// `electrodos-*` observations and the metric shows up twice.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
const codigos = detalle.eeg!.alteraciones.map(a => a.codigo);
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
});
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect(detalle.eeg!.edad_meses).toBe(23.6);
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
});
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const relacion = (await answer).relacion_ados2!;
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,
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
});
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
// the chart and the panel. Fails if the adapter fills them with defaults.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect('edad_meses' in detalle.eeg!).toBe(false);
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
expect('relacion_ados2' in detalle).toBe(false);
});
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => { it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no // Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes. // value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
@@ -13,6 +13,7 @@ import {
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR, CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA, GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
} from './indicadores-cama-fhir'; } from './indicadores-cama-fhir';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical // The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked // sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
@@ -40,8 +41,8 @@ const POPULATION_GROUP: Record<string, string> = {
}; };
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures // `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`). // and CaCu's have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`, `CACU-EU7` -> `cacu_eu7`).
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_'); export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? CACU_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code); const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
// Age groups travel as `16_23`; the page names them `16-23`. // Age groups travel as `16_23`; the page names them `16-23`.
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value; export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
@@ -56,10 +57,21 @@ function decimal(score: Score | undefined, name: string): number | null {
} }
const round1 = (value: number) => Math.round(value * 10) / 10; const round1 = (value: number) => Math.round(value * 10) / 10;
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
// keeps every category ungrouped.
export function categorias(measure: Measure): Record<string, Categoria> { export function categorias(measure: Measure): Record<string, Categoria> {
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => { return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString; const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : []; return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null,
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
}));
}
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
// when the Measure declares none.
export function gruposDeCategoria(measure: Measure): Record<string, string> {
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
})); }));
} }
function contrato(measure: Measure): string { function contrato(measure: Measure): string {
@@ -193,6 +205,34 @@ function cruceDeHistopatologia(group: Group, estrato: string): Map<string, numbe
return celdas; return celdas;
} }
// A composition (C2) by one of its strata, from the report's stratifier that crosses the stratum with the category
// (`[estrato, categoria]`, as the WebApi publishes it): each stratum value with its caption, and each cell's count.
// FHIR lists only the cells that have units and the report is complete, so a cell it doesn't list is a zero; a stratum
// value nobody falls in isn't listed at all. A report with no units has no cell to cross. A missing component, a
// category the Measure doesn't declare, a repeated cell or cells that don't add up to the period's units are contract
// errors, never a silent zero. FHIR publishes no suppression marker, so nothing here is read as suppressed.
function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly string[]) {
const unidades = count(group.population, 'initial-population');
const valores = new Map<string, string>(), celdas = new Map<string, number>();
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
if (!stratifier && unidades === 0) return { valores, celdas };
if (!stratifier) throw new Error('Dimensión no admitida');
let suma = 0;
for (const stratum of stratifier.stratum ?? []) {
const del = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
const valor = code(del?.value), categoria = code(cat?.value), n = stratum.population?.[0]?.count;
if (!valor || !categoria || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) throw new Error('Celda del estrato incompleta');
if (!declaradas.includes(categoria)) throw new Error('Categoría no declarada en el estrato');
const e = estratoValor(valor), clave = `${e}|${categoria}`;
if (celdas.has(clave)) throw new Error('Celda del estrato repetida');
if (!valores.has(e)) valores.set(e, display(del!.value) ?? e);
celdas.set(clave, n);
suma += n;
}
if (unidades !== null && suma !== unidades) throw new Error('Los conteos por estrato no suman las unidades del periodo');
return { valores, celdas };
}
// The `/datos` answer for `measure`, from one report per period. // The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos { export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id); const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
@@ -200,6 +240,8 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>(); const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above). // The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads'; const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
// Any other composition asked by a stratum is read from its crossed stratifier (`cruceDeComposicion`).
const porEstrato = kind === 'C2' && estrato !== undefined && !cruzado;
const cats: Record<string, Categoria> = cruzado const cats: Record<string, Categoria> = cruzado
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => { ? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo]; const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
@@ -241,6 +283,21 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
}); });
continue; continue;
} }
if (porEstrato) {
const declaradasEnOrden = Object.keys(cats);
const { valores: delPeriodo, celdas } = cruceDeComposicion(group, estrato!, declaradasEnOrden);
for (const [e, etiqueta] of delPeriodo) {
let total = 0;
declaradasEnOrden.forEach((categoria, orden) => {
const n = celdas.get(`${e}|${categoria}`) ?? 0;
total += n;
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
});
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
if (!valores.has(e)) valores.set(e, etiqueta);
}
continue;
}
if (kind === 'C2') { if (kind === 'C2') {
const strata = group.stratifier?.[0]?.stratum ?? []; const strata = group.stratifier?.[0]?.stratum ?? [];
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0])); const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
@@ -280,10 +337,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
periodos, periodos,
estrato: estrato ?? null, estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }), ...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado ? { totales_estrato: totales } : {}), ...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
grupos, grupos,
categorias: cats, categorias: cats,
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {}, grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
notas: [], notas: [],
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))), reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
filas, filas,
@@ -1,6 +1,8 @@
// Presentation labels for representations confirmed in the published catalog. // Presentation labels for representations confirmed in the published catalog.
// Exact IDs remain the option values and HTTP identities; never infer a type // 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. // 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';
const FIGURE_LABELS: Readonly<Record<string, string>> = { const FIGURE_LABELS: Readonly<Record<string, string>> = {
fig_c1_barras_alteracion: 'Barras por alteración', fig_c1_barras_alteracion: 'Barras por alteración',
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad', fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
@@ -79,11 +79,15 @@ describe('Histórico de CaMa', () => {
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort()); expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false); expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false);
}); });
it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => { it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
montar(CATALOGO, true); responder(); 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(HISTORICO_CAMA.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent); const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']); expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']);
expect(paneles()).toHaveLength(7);
const titulo = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo);
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
expect(graficas()).toHaveLength(5); expect(graficas()).toHaveLength(5);
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0); expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
}); });
@@ -87,7 +87,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } }); expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
expect(r.comoLeer).toContain('mastografías'); expect(r.comoLeer).toContain('mastografías');
}); });
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => { it('Pacientes evaluadas con BI-RADS 4, 5 o 6 conserva la gráfica y omite la explicación de la barra', () => {
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' })); const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
expect(pacientes.comoLeer).toBe(''); expect(pacientes.comoLeer).toBe('');
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']); expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
@@ -14,12 +14,9 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette. // 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] }; const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
// CaMa's day-count lines sit next to the histopathology bars, so they borrow that figure's blue, purple and rose. // CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
const DIAS: Readonly<Record<string, { claro: string; oscuro: string; relleno: string }>> = { const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
cama_dias_toma_diagnostico: { claro: '#2F6DB3', oscuro: '#9DBFE3', relleno: '#9DBFE380' }, const FONDO_AZUL = '#9DBFE380';
cama_eu38a: { claro: '#9C42C2', oscuro: '#D2A4EA', relleno: '#9C42C240' },
cama_dias_resultado_diagnostico: { claro: '#C24269', oscuro: '#E7A3B8', relleno: '#C2426940' },
};
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right. // sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
@@ -92,17 +89,24 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
return { validas, suprimidos, sinDato }; return { validas, suprimidos, sinDato };
} }
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null); 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.
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 };
const linea = c2Theme(tema).line;
return { linea, relleno: linea + '40' };
}
type Trazo = Omit<HistoricoFigura, 'contrato'>; type Trazo = Omit<HistoricoFigura, 'contrato'>;
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data); const periodos = validar(data);
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here. // 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 { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line; const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
return { return {
figure: { data: [ figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea), banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 }, { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''), text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' }, hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
@@ -113,13 +117,11 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
const periodos = validar(data), unidad = unidadDe(data); const periodos = validar(data), unidad = unidadDe(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const propio = DIAS[data.id]; const trazo = colorDeLinea(data.id, tema);
const linea = propio ? (tema === 'oscuro' ? propio.oscuro : propio.claro) : c2Theme(tema).line;
const relleno = propio && tema === 'claro' ? propio.relleno : linea + '40';
return { return {
figure: { data: [ figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea, relleno), banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', trazo.linea, trazo.relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 }, marker: { color: linea }, { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''), text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' }, hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => { ], layout: (() => {
@@ -63,15 +63,19 @@ describe('Figuras de histórico', () => {
expect(traza(data, 0).y).toEqual([30, 10]); expect(traza(data, 0).y).toEqual([30, 10]);
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]); expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
}); });
it('las líneas de días de CaMa usan el azul, el morado y el rosa de la histopatología', () => { it('las líneas de CaMa comparten el morado y, si hay banda, el fondo azul', () => {
const color = (id: string, tema: 'claro' | 'oscuro') => { const dias = (id: string, tema: 'claro' | 'oscuro') => {
const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure; const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure;
return { linea: (figure.data[1]['line'] as { color: string }).color, banda: figure.data[0]['fillcolor'] }; return { linea: (figure.data[1]['line'] as { color: string }).color, puntos: (figure.data[1]['marker'] as { color: string }).color, banda: figure.data[0]['fillcolor'] };
}; };
expect(color('cama_dias_toma_diagnostico', 'claro')).toEqual({ linea: '#2F6DB3', banda: '#9DBFE380' }); for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
expect(color('cama_eu38a', 'claro')).toEqual({ linea: '#9C42C2', banda: '#9C42C240' }); expect(dias(id, 'claro')).toEqual({ linea: '#9C42C2', puntos: '#9C42C2', banda: '#9DBFE380' });
expect(color('cama_dias_resultado_diagnostico', 'claro')).toEqual({ linea: '#C24269', banda: '#C2426940' }); }
expect(color('cama_dias_toma_diagnostico', 'oscuro').linea).toBe('#9DBFE3'); expect(dias('cama_dias_toma_diagnostico', 'oscuro')).toEqual({ linea: '#D2A4EA', puntos: '#D2A4EA', banda: '#9DBFE380' });
const tasa = historicoFigura({ ...base, id: 'cama_confirmacion_birads45', contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure;
expect((tasa.data[1]['line'] as { color: string }).color).toBe('#9C42C2');
expect((tasa.data[1]['marker'] as { color: string }).color).toBe('#9C42C2');
expect(tasa.data[0]['fillcolor']).toBe('#9DBFE380');
}); });
it('las líneas usan el verde legible en cada tema', () => { it('las líneas usan el verde legible en cada tema', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }; const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
@@ -14,6 +14,7 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore
import { IndicadoresPeriodos } from './indicadores-periodos'; import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service'; import { IndicadoresService } from './indicadores.service';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
@@ -27,13 +28,12 @@ const PERSONALIZADO = -1;
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible. // publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' }, { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' }, { id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' }, { id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
{ id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' },
]; ];
// The screening steps go together as small charts, and the case counts are followed by their in-process share. // The screening steps go together as small charts, and the case counts are followed by their in-process share.
@@ -62,7 +62,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
selector: 'app-indicadores-historico', selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: ` template: `
<div class="controles"> <div class="controles compacto">
<h2>Filtros</h2> <h2>Filtros</h2>
<div class="controles-fila"> <div class="controles-fila">
<div class="interval"> <div class="interval">
@@ -127,10 +127,22 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
</div> </div>
`, `,
styles: ` styles: `
@use '@angular/material' as mat;
:host { display: block; min-width: 0; } :host { display: block; min-width: 0; }
.controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); .controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; } .controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
// Same field height as the summary filters. The theme also rewrites corners, which would turn the switch into a pill.
.controles.compacto {
@include mat.theme((density: -4));
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
--mat-sys-corner-full: 4px;
}
.controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); } .controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; } .interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; } .interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; }
@@ -151,7 +163,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); } .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)); } } @container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
h3 { margin: 0; font: var(--mat-sys-title-small); } h3 { margin: 0; font: var(--mat-sys-title-small); }
mat-form-field { flex: 0 1 14rem; width: 14rem; min-width: 14rem; max-width: 24rem; } mat-form-field { flex: 0 1 14rem; min-width: 0; max-width: 24rem; }
`, `,
}) })
export class IndicadoresHistorico { export class IndicadoresHistorico {
@@ -47,7 +47,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => { it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => {
if (domain === 'cama') { if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente'); expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6'); expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 o 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']); expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
} else expect(anchor.id).toBe('cacu_eu7'); } else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0])); const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
@@ -14,7 +14,7 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true, id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
}; };
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = { export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
}; };
// Institutional definitions retained for consumers outside the opportunity strip. // Institutional definitions retained for consumers outside the opportunity strip.
export const CAMA_CONFIRMACION_KPI: KpiDefinition = { export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
@@ -25,7 +25,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
}; };
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = { export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%', id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`, c1Info: (n, d) => `${n} de ${d} biopsias con riesgo a carcinoma.`,
}; };
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = { export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
@@ -58,7 +58,7 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, { id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
], ],
cama: [ cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', contrato: 'C2', unit: 'pacientes' },
CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI,
], ],
}; };
@@ -4,8 +4,7 @@
<h1 id="dashboard-title">Ficha del paciente</h1> <h1 id="dashboard-title">Ficha del paciente</h1>
<p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p> <p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
} @else { } @else {
@if (dominio !== 'cama') { <span class="domain">{{ domainTitles[dominio] }}, investigación</span> } <h1 id="dashboard-title">{{ domainTitles[dominio] }}</h1>
<h1 id="dashboard-title">{{ dominio === 'cama' ? 'Cáncer de mama' : 'Indicadores' }}</h1>
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p> <p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
} }
</header> </header>
@@ -23,10 +22,7 @@
@if (!catalogLoading() && filters; as state) { @if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio"> <section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">Filtros</h2> <h2 id="global-filters-title" class="section-title">Filtros</h2>
@if (dominio !== 'cama') { <app-indicador-period-filters [state]="state" [compact]="true" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
}
<app-indicador-period-filters [state]="state" [compact]="dominio === 'cama'" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()" (retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" /> (edited)="editFilters()" (apply)="applyFilters()" />
</section> </section>
@@ -50,7 +46,10 @@
@if (kpis.length && !initialPeriodBlocked) { @if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio"> <section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@let resumen = teaResumenPeriodo; @let resumen = teaResumenPeriodo;
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2> <div class="kpi-heading">
<h2 id="kpi-section-title" class="section-title">Indicadores de oportunidad</h2>
@if (periodoCompartido) { <p class="kpi-period">Periodo {{ periodoCompartido }}</p> }
</div>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> } @if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. --> <!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)"> <div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
@@ -76,7 +75,7 @@
<section class="graphic-section" aria-labelledby="graphic-section-title"> <section class="graphic-section" aria-labelledby="graphic-section-title">
<div class="catalog-heading"> <div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2> <h2 id="graphic-section-title" class="section-title">Indicadores clínicos</h2>
</div> </div>
@if (catalogLoading()) { @if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" /> <mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
@@ -6,17 +6,16 @@
.dashboard { max-width: 1680px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; } .dashboard { max-width: 1680px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; } h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
.state { padding: 1.25rem; margin: 0; } .state { padding: 1.25rem; margin: 0; }
// CaMa's filter block is one compact row, as in the reference. .global-filters .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
.global-filters[data-domain='cama'] { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); }
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; } .section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; } .section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
.kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2); .kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2);
padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border); padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); background: var(--issste-surface); } border-radius: var(--issste-radius); background: var(--issste-surface); }
.kpi-section > .section-title { margin-bottom: var(--issste-space-4); } .kpi-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: var(--issste-space-3); }
.kpi-section > .kpi-heading { margin-bottom: var(--issste-space-4); }
.kpi-period { margin: .15rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; white-space: nowrap; }
.graphic-section { margin-top: var(--issste-space-6); } .graphic-section { margin-top: var(--issste-space-6); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; } .kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
@@ -37,16 +36,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
h1 { font-size: 1.5rem; } h1 { font-size: 1.5rem; }
} }
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; } .global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } @container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
.kpi-section[data-domain='cama'] .kpi-grid { grid-auto-rows: 1fr; } .kpi-section .kpi-grid { grid-auto-rows: 1fr; }
@container dashboard (min-width: 1350px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(5, minmax(0, 1fr)); } } @container dashboard (min-width: 1350px) { .kpi-section .kpi-grid { grid-template-columns: repeat(min(5, var(--kpi-count)), minmax(0, 1fr)); } }
.kpi-section[data-domain='cacu'] .kpi-grid {
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
align-items: stretch;
}
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1); .section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border); border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
@@ -54,15 +54,15 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
}); });
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => { it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
load(); load();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores'); expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Trastorno del espectro autista');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4); expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges(); fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente'); expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de TEA'); expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de trastorno del espectro autista');
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull(); expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title'); expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges(); fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores'); expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Trastorno del espectro autista');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4); expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento'); expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
expect(page.activeSection()).toBe('resumen'); expect(page.activeSection()).toBe('resumen');
@@ -107,7 +107,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(host.querySelector('mat-select')).toBeNull(); expect(host.querySelector('mat-select')).toBeNull();
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
expect(host.textContent).not.toContain('Contrato C1'); expect(host.textContent).not.toContain('Contrato C1');
expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); expect(host.querySelector('.catalog-metadata')).toBeNull();
expect(host.querySelector('.pin-toggle')).toBeNull();
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('Resumen omite los indicadores publicados solo para otra pestaña', () => { it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
@@ -122,7 +123,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
const header = host.querySelector('header'); toggle(); flushAll(); const header = host.querySelector('header'); toggle(); flushAll();
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges(); const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel); expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel);
expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true); expect(host.querySelector('.catalog-metadata')).toBeNull(); http.expectNone(() => true);
}); });
it('UX-06C: conserva título largo completo y el control separado de la identidad', () => { it('UX-06C: conserva título largo completo y el control separado de la identidad', () => {
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive'; const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
@@ -131,7 +132,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(header.querySelector('h2')?.textContent).toBe(title); expect(header.querySelector('h2')?.textContent).toBe(title);
expect(header.querySelector('.card-identity button')).toBeNull(); expect(header.querySelector('.card-identity button')).toBeNull();
expect(header.querySelector('button')).toBeNull(); expect(header.querySelector('button')).toBeNull();
expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title); expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('UX-06B la navegación entre dominios es la del encabezado: la página no la duplica', () => { it('UX-06B la navegación entre dominios es la del encabezado: la página no la duplica', () => {
@@ -324,7 +325,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
toggle(index); toggle(index); flushAll(); await fixture.whenStable(); toggle(index); toggle(index); flushAll(); await fixture.whenStable();
expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos'); expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos');
const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'saveGlobal'); const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'saveGlobal');
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!; expect(fixture.debugElement.queryAll(By.directive(MatSelect)).some(e => e.componentInstance.multiple)).toBe(false);
const select = fixture.debugElement.query(By.directive(MatSelect));
const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue'); const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue');
for (let i = 0; i < 3; i++) { for (let i = 0; i < 3; i++) {
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable(); select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
@@ -32,6 +32,7 @@ import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis'; import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico'; import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente'; import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
@@ -101,6 +102,14 @@ export class IndicadoresPage {
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect'); private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly graphicCards = viewChildren(IndicadorCatalogCard); private readonly graphicCards = viewChildren(IndicadorCatalogCard);
readonly kpiPanels = viewChildren(IndicadorKpiPanel); readonly kpiPanels = viewChildren(IndicadorKpiPanel);
// The opportunity cards share the period their own query already resolved.
get periodoCompartido(): string {
const deConsulta = this.kpiPanels().map(panel => panel.temporalReference.trim())
.find(text => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(text));
if (deConsulta) return deConsulta;
const applied = this.filters?.applied;
return applied?.selection.mode === 'explicit' && applied.selection.periodos.length === 1 ? applied.selection.periodos[0] : '';
}
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>(); private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
private renderedCards: readonly IndicadorCatalogCard[] = []; private renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver; private visibilityObserver?: IntersectionObserver;
@@ -292,9 +301,12 @@ export class IndicadoresPage {
private readonly destroyRef = inject(DestroyRef); private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute, { optional: true }); private readonly route = inject(ActivatedRoute, { optional: true });
dominio: Dominio = 'tea'; dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' }; readonly domainLabels: Record<Dominio, string> = {
// At the start of the header line. tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' }; };
readonly domainTitles: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
};
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] }; readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); } figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); } independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
@@ -346,9 +358,9 @@ export class IndicadoresPage {
readonly catalog = signal<Indicador[]>([]); readonly catalog = signal<Indicador[]>([]);
// Ids of the indicators to render; null shows the whole catalog. // Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null); readonly indicatorSelection = signal<string[] | null>(null);
// CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws. // The summary follows CaMa's mockup: no search box and no pins in any domain.
readonly searchVisible = computed(() => { const total = this.catalogOrder().length; return this.dominio !== 'cama' && total >= 2; }); readonly searchVisible = computed(() => false);
// Stable presentation priority; pins still take precedence in the grid. // Stable presentation order. Pins no longer reorder the summary.
readonly catalogOrder = computed(() => { readonly catalogOrder = computed(() => {
const catalog = this.catalog(); const catalog = this.catalog();
return this.dominio === 'cacu' return this.dominio === 'cacu'
@@ -365,8 +377,7 @@ export class IndicadoresPage {
}); });
readonly searchResults = computed(() => { readonly searchResults = computed(() => {
const selected = new Set(this.selectedIndicators()); const selected = new Set(this.selectedIndicators());
const items = this.catalogOrder().filter(item => selected.has(item.id)); return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
}); });
readonly catalogLoading = signal(true); readonly catalogLoading = signal(true);
readonly catalogError = signal(''); readonly catalogError = signal('');
@@ -483,7 +494,8 @@ export class IndicadoresPage {
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false); this.catalogLoading.set(false);
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined; this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
this.catalog.set(items); this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia'
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items);
this.filtersEdited(); this.filtersEdited();
this.catalogError.set(error); this.catalogError.set(error);
this.availabilityRequests.next(); this.availabilityRequests.next();
@@ -97,14 +97,17 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges(); const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']); expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull(); expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador'); expect(fixture.nativeElement.querySelector('.fields.compact')).not.toBeNull();
expect(fixture.nativeElement.textContent).not.toContain('Existe reporte en al menos un indicador');
expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); fixture.componentInstance.applyFilters(); fixture.detectChanges();
const single = flushDatos('cacu'); expect(single).toHaveLength(2); const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true); expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true); control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
expect(control.selectedPeriods).toEqual(['2025-10']); expect(control.selectedPeriods).toEqual(['2025-02']);
fixture.componentInstance.applyFilters(); fixture.detectChanges(); fixture.componentInstance.applyFilters(); fixture.detectChanges();
const replaced = flushDatos('cacu');
expect(replaced.every(r => r.request.params.get('periodos') === '2025-02')).toBe(true);
expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true); expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
http.expectNone(() => true); http.expectNone(() => true);
await fixture.whenStable(); await fixture.whenStable();
@@ -35,46 +35,40 @@ describe('UX-06E.D.3.B fijación temporal', () => {
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function card(id: string) { return cards().find(c => c.indicador.id === id)!; } function card(id: string) { return cards().find(c => c.indicador.id === id)!; }
function ids() { return cards().map(c => c.indicador.id); } function ids() { return cards().map(c => c.indicador.id); }
function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; }
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); } async function pin(id: string) { page.togglePinned(card(id).indicador); fixture.detectChanges(); await settle(); }
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); }
it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => { it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
const control = button('i3'); expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0); await pin('i3');
expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(control.getAttribute('aria-label')).toContain('Fijar indicador'); expect(ids()).toEqual(items.map(i => i.id));
for (const key of ['Enter', ' ']) { await pin('i3');
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); expect(ids()).toEqual(items.map(i => i.id));
}
await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true');
expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador');
await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false');
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => { it('varios fijados no alteran el orden del catálogo', async () => {
const original = page.catalog(), snapshot = JSON.stringify(original); const original = page.catalog(), snapshot = JSON.stringify(original);
await pin('i4'); await pin('i2'); await pin('i0'); await pin('i4'); await pin('i2'); await pin('i0');
expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']); expect(ids()).toEqual(items.map(i => i.id));
await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']); await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true); expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
}); });
it('la selección de indicadores conserva la prioridad de los fijados', async () => { it('la selección de indicadores conserva el orden del catálogo', async () => {
await pin('i3'); await pin('i4'); await pin('i3'); await pin('i4');
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle(); page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i3', 'i4', 'i1']); expect(ids()).toEqual(['i1', 'i3', 'i4']);
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']); await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
expect(cards()).toHaveLength(3); http.expectNone(() => true); expect(cards()).toHaveLength(3); http.expectNone(() => true);
}); });
it('Mostrar todos restaura el catálogo con los fijados primero', async () => { it('Mostrar todos restaura el catálogo en su orden', async () => {
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle(); await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0']); expect(ids()).toEqual(['i0']);
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true); page.showAllIndicators(); fixture.detectChanges(); await settle();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
}); });
it('un fijado sin seleccionar no se muestra', async () => { it('un fijado sin seleccionar no se muestra', async () => {
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle(); await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
@@ -82,11 +76,16 @@ describe('UX-06E.D.3.B fijación temporal', () => {
}); });
it('memoria independiente por dominio y persistente al recrear la página', async () => { it('memoria independiente por dominio y persistente al recrear la página', async () => {
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id)); await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
// CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins.
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id)); await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); const memory = TestBed.inject(IndicadoresMemory);
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3'); expect(memory.isPinned('cacu', 'i1')).toBe(true);
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true); expect(memory.isPinned('tea', 'i3')).toBe(true);
expect(memory.isPinned('cama', 'i1')).toBe(false);
page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
page.changeDominio('tea'); load(); expect(ids()).toEqual(items.map(i => i.id));
fixture.destroy(); create(); load();
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
}); });
it('no usa Storage y una nueva memoria reinicia la fijación', async () => { it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem'); const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
@@ -94,10 +93,12 @@ describe('UX-06E.D.3.B fijación temporal', () => {
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false); expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true); expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
}); });
it('mover la tarjeta conserva foco en su botón existente', async () => { it('fijar no mueve la tarjeta ni pide figuras', async () => {
const control = button('i4'); control.focus(); await pin('i4'); const before = cards();
expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control); await pin('i4');
await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true); expect(cards()).toEqual(before);
await pin('i4');
expect(cards()).toEqual(before); http.expectNone(() => true);
}); });
it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => { it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => {
card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle(); card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle();
@@ -4,7 +4,6 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';
import { IndicadoresPage } from './indicadores-page'; import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigurePanel } from './indicador-figure-panel';
@@ -40,24 +39,20 @@ describe('Selección de indicadores gráficos', () => {
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function ids() { return cards().map(c => c.indicador.id); } function ids() { return cards().map(c => c.indicador.id); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); } function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: catálogo de %i', count => { it.each([0, 1, 2, 5])('no ofrece buscador y muestra el catálogo completo: %i indicadores', count => {
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count); expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(cards()).toHaveLength(count);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('lista todo el catálogo, con todos seleccionados al inicio', () => { it('lista todo el catálogo, con todos seleccionados al inicio', () => {
load(); load();
expect(select()!.multiple).toBe(true); expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
expect(page.selectedIndicators()).toEqual(items.map(i => i.id)); expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
expect(page.selectionSummary()).toBe('Todos los indicadores'); expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(result()).toBe('Mostrando 5 de 5 indicadores.'); expect(fixture.nativeElement.textContent).not.toContain('Mostrando 5 de 5 indicadores.');
expect(showAll().disabled).toBe(true);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => { it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
@@ -66,7 +61,6 @@ describe('Selección de indicadores gráficos', () => {
expect(ids()).toEqual(['B02', 'E05']); expect(ids()).toEqual(['B02', 'E05']);
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]); expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores'); expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados'); expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo'); choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
expect(page.catalog()).toBe(original); expect(page.catalog()).toBe(original);
@@ -76,9 +70,8 @@ describe('Selección de indicadores gráficos', () => {
load(); choose([]); load(); choose([]);
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0); expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados'); expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
expect(showAll().disabled).toBe(false); page.showAllIndicators(); fixture.detectChanges();
showAll().click(); fixture.detectChanges(); expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
http.expectNone(() => true); http.expectNone(() => true);
}); });
it('marcar todos equivale a no filtrar', () => { it('marcar todos equivale a no filtrar', () => {
@@ -90,26 +83,18 @@ describe('Selección de indicadores gráficos', () => {
choose(['A01']); choose(['A01']);
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis); expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
}); });
it('«Ir» lleva a la tarjeta sin alternar la opción y muestra el indicador si estaba oculto', async () => { it('ir a un indicador oculto lo vuelve a mostrar y desplaza hasta su tarjeta', async () => {
const scroll = vi.fn(); const scroll = vi.fn();
Element.prototype.scrollIntoView = scroll; Element.prototype.scrollIntoView = scroll;
load(); choose(['A01']); load(); choose(['A01']);
select()!.open(); fixture.detectChanges(); await fixture.whenStable(); expect(document.querySelector('.indicator-select-panel')).toBeNull();
const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go')) page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable();
.find(a => a.closest('mat-option')!.textContent!.includes(items.find(i => i.id === id)!.titulo))!;
expect(go('D04').getAttribute('aria-label')).toBe('Ir a Seguimiento');
// The scroll waits until the panel has finished closing.
const settle = (calls: number) => vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(calls); });
go('D04').click(); fixture.detectChanges(); await fixture.whenStable();
expect(page.selectedIndicators()).toEqual(['A01', 'D04']); expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
expect(select()!.panelOpen).toBe(false); await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); });
await settle(1);
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento'); expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
select()!.open(); fixture.detectChanges(); await fixture.whenStable(); page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable();
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
// Already visible: the selection is untouched.
expect(page.selectedIndicators()).toEqual(['A01', 'D04']); expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
await settle(2); await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(2); });
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} })); http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
}); });
it('no muestra el botón flotante de navegación por indicadores', () => { it('no muestra el botón flotante de navegación por indicadores', () => {
@@ -10,6 +10,13 @@ export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
} }
// Whether a composition declares `estrato` among its strata: the catalog from FHIR carries the Measure's declared strata
// (`estratos`) and no local filters. Only views that read one fixed stratum use it (CaCu's EU7 by follow-up status);
// it doesn't turn on stratified figures or filters for other C2 measures.
export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): boolean {
const declarados = (item as Indicador & { estratos?: unknown }).estratos;
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato);
}
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } { export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
@@ -61,15 +61,23 @@
@if (teaData; as response) { @if (teaData; as response) {
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo"> <section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3> <h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
<dl> @if (response.resumen_eeg.validadas) {
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div> <dl>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div> <div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div> <div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) { <div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div> @for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
} <div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
</dl> }
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p> </dl>
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
} @else {
<dl>
<div><dt>Con EEG válido</dt><dd>{{ response.resumen_eeg.con_eeg_valido }}</dd></div>
<div><dt>Sin EEG válido</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
</dl>
<p>Las alteraciones del EEG se muestran cuando se validen sus curvas de referencia.</p>
}
</section> </section>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0"> <div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table> <table>
@@ -12,7 +12,7 @@ import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'
import { Dominio } from './indicadores.models'; import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad'; import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service'; import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service'; import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen'; import { TeaPacienteResumen } from './tea-paciente-resumen';
@Component({ @Component({
@@ -98,6 +98,8 @@ export class IndicadoresTracking implements OnChanges {
if (result.data) { if (result.data) {
const data = result.data; const data = result.data;
this.tiposAlteracion = data.tipos_alteracion; this.tiposAlteracion = data.tipos_alteracion;
// Until the alterations are validated, the EEG filter can only tell a valid EEG from none.
this.statuses = data.resumen_eeg.validadas ? ALTERACIONES_EEG : EEG_VALIDO;
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size }; this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied }; this.draft = { ...this.applied };
} }
@@ -186,11 +186,11 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render(); const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0])); page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
observer().emit(target); await idle(); http.expectNone(() => true); observer().emit(target); await idle(); http.expectNone(() => true);
// The pinned indicator leads; the other selected one keeps its component. // Pins no longer reorder; the selected indicators keep catalog order and their components.
expect(cards()).toEqual([before[4], before[3]]); expect(cards()).toEqual([before[3], before[4]]);
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm(); positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render(); http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
expect(cards()[1].selectedFigure).toBe('f'); expect(cards()[0].selectedFigure).toBe('f');
}); });
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => { it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
@@ -142,6 +142,23 @@ describe('UX-04 validación defensiva HTTP', () => {
describe('contrato datos exclusivo de KPI', () => { describe('contrato datos exclusivo de KPI', () => {
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
it('conserva los conteos, totales y celdas suprimidas que publica WebApi para mastografías de CaMa', () => {
const http = TestBed.inject(HttpTestingController);
const payload = {
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'],
filas: [
{ periodo: '2025-S1', categoria: 'BIRADS_4', n: 15, suprimido: 0 },
{ periodo: '2025-S1', categoria: 'BIRADS_5', n: 0, suprimido: 0 },
{ periodo: '2025-S2', categoria: 'BIRADS_4', n: null, suprimido: 1 },
],
totales_estrato: [{ periodo: '2025-S1', estrato: 'BIRADS_4', n: 15, suprimido: 0 }],
};
let result: unknown;
TestBed.inject(IndicadoresService).datos('cama', payload.id, 'semestre', payload.periodos).subscribe(value => result = value);
http.expectOne(req => req.url === `/cama/indicadores/${payload.id}/datos`).flush(payload);
expect(result).toEqual(payload);
http.verify();
});
it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => { it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => {
const http = TestBed.inject(HttpTestingController); let result: unknown; const http = TestBed.inject(HttpTestingController); let result: unknown;
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v); TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
@@ -0,0 +1,76 @@
// Covers the histologic-type classification and its column in the follow-up table. It uses the CaMa follow-up
// fixture (fixtures/cama_seguimiento.json), to which each test adds a synthetic `tipo_histologico` per row.
import fixtureData from './fixtures/cama_seguimiento.json';
import { clasificacionHistologica, MAPEO_HISTOLOGICO, SIN_CLASIFICAR } from './mapeo-histologico';
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
const respuesta = () => structuredClone(fixtureData) as unknown as { columnas: { clave: string; etiqueta: string }[]; items: Record<string, string | number | null>[] };
describe('Clasificación histológica', () => {
it.each([
['Ductal (NST)', 'Carcinoma invasor'], ['Lobulillar', 'Carcinoma invasor'], ['Ductal-lobulillar mixto', 'Carcinoma invasor'],
['Mucinoso', 'Carcinoma invasor'], ['Paget', 'Carcinoma in situ'], ['Papilar', 'Revisar (Benigno / In situ / Invasor)'],
['Tubular', 'Carcinoma invasor'], ['cribiforme', 'Revisar (In situ / Invasor)'], ['Micropapilar', 'Revisar (In situ / Invasor)'],
['Inflamatorio', 'Carcinoma invasor'], ['Medular', 'Carcinoma invasor'], ['Otros', 'Revisar (Benigno / In situ / Invasor)'],
['SIN MAPEAR', 'Sin clasificar'],
])('asigna a «%s» la clasificación «%s»', (tipo, clasificacion) => {
// Fails if a type is moved to another group or dropped from the mapping.
expect(clasificacionHistologica(tipo)).toBe(clasificacion);
});
it('la categoría combinada «Tubular / cribiforme» del gráfico es carcinoma invasor', () => {
// Fails if the chart's merged category stops being classified, which would leave its patients unclassified.
expect(clasificacionHistologica('Tubular / cribiforme')).toBe('Carcinoma invasor');
});
it('un tipo fuera del mapeo, incluido uno heredado del prototipo de objeto, es «Sin clasificar»', () => {
// Fails if the lookup returns inherited properties such as «constructor» instead of the fallback.
for (const tipo of ['Desconocido', '', 'constructor', 'toString']) expect(clasificacionHistologica(tipo)).toBe(SIN_CLASIFICAR);
});
it('el mapeo conserva sus trece tipos y sus cuatro clasificaciones directas', () => {
// Fails if a type is added or removed without reviewing its classification.
expect(Object.keys(MAPEO_HISTOLOGICO)).toHaveLength(14);
expect(new Set(Object.values(MAPEO_HISTOLOGICO))).toEqual(new Set([
'Carcinoma invasor', 'Carcinoma in situ', 'Revisar (Benigno / In situ / Invasor)', 'Revisar (In situ / Invasor)', 'Sin clasificar']));
});
});
describe('Seguimiento: columna de clasificación histológica', () => {
const tipos = ['Ductal (NST)', 'Paget', 'Otros', 'SIN MAPEAR', 'Zzz'];
it('cada paciente recibe la clasificación de su propio tipo, en una columna tras el tipo o tras el resultado de la biopsia', () => {
// Fails if the classification is computed from another row or placed away from the biopsy columns.
const datos = respuesta();
const conBiopsia = datos.items.filter(item => item['biopsia'] !== null);
conBiopsia.forEach((item, i) => { item['tipo_histologico'] = tipos[i % tipos.length]; });
const r = seguimientoTablaResponse(datos);
const claves = r.columnas.map(c => c.clave);
expect(claves[claves.indexOf('biopsia') + 1]).toBe('clasificacion_histologica');
expect(r.columnas.find(c => c.clave === 'clasificacion_histologica')!.etiqueta).toBe('Clasificación histológica');
for (const item of r.items.filter(item => typeof item['tipo_histologico'] === 'string')) {
expect(item['clasificacion_histologica']).toBe(clasificacionHistologica(item['tipo_histologico'] as string));
}
});
it('con una columna de tipo, la clasificación va justo después de ella', () => {
// Fails if the derived column ignores the type's own column and lands elsewhere.
const datos = respuesta();
datos.columnas.splice(datos.columnas.findIndex(c => c.clave === 'biopsia') + 1, 0, { clave: 'tipo_histologico', etiqueta: 'Tipo histológico' });
datos.items.forEach(item => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Lobulillar'; });
const claves = seguimientoTablaResponse(datos).columnas.map(c => c.clave);
expect(claves.slice(claves.indexOf('tipo_histologico'), claves.indexOf('tipo_histologico') + 2)).toEqual(['tipo_histologico', 'clasificacion_histologica']);
});
it('un paciente sin tipo no recibe clasificación y los demás campos quedan como llegaron', () => {
// Fails if a patient without biopsy is shown as «Sin clasificar», or if other row values are altered.
const datos = respuesta();
datos.items.forEach((item, i) => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Medular'; });
const original = structuredClone(datos.items);
const r = seguimientoTablaResponse(datos);
r.items.forEach((item, i) => {
if (original[i]['tipo_histologico'] === null) expect('clasificacion_histologica' in item).toBe(false);
expect({ ...item, clasificacion_histologica: undefined }).toEqual({ ...original[i], clasificacion_histologica: undefined });
});
});
it('una lista sin tipo histológico no cambia', () => {
// Fails if the column appears while the API does not send the field.
const r = seguimientoTablaResponse(respuesta());
expect(r.columnas.map(c => c.clave)).not.toContain('clasificacion_histologica');
expect(r.items.some(item => 'clasificacion_histologica' in item)).toBe(false);
});
});
@@ -0,0 +1,23 @@
// Groups the histologic type of a biopsy into the classification shown beside it.
export const SIN_CLASIFICAR = 'Sin clasificar';
export const MAPEO_HISTOLOGICO: Readonly<Record<string, string>> = {
'Ductal (NST)': 'Carcinoma invasor',
'Lobulillar': 'Carcinoma invasor',
'Ductal-lobulillar mixto': 'Carcinoma invasor',
'Mucinoso': 'Carcinoma invasor',
'Paget': 'Carcinoma in situ',
'Papilar': 'Revisar (Benigno / In situ / Invasor)',
'Tubular': 'Carcinoma invasor',
'Tubular / cribiforme': 'Carcinoma invasor',
'cribiforme': 'Revisar (In situ / Invasor)',
'Micropapilar': 'Revisar (In situ / Invasor)',
'Inflamatorio': 'Carcinoma invasor',
'Medular': 'Carcinoma invasor',
'Otros': 'Revisar (Benigno / In situ / Invasor)',
'SIN MAPEAR': SIN_CLASIFICAR,
};
/** The classification of a histologic type; a type outside the mapping is «Sin clasificar». */
export const clasificacionHistologica = (tipo: string) =>
Object.hasOwn(MAPEO_HISTOLOGICO, tipo) ? MAPEO_HISTOLOGICO[tipo] : SIN_CLASIFICAR;
@@ -4,6 +4,7 @@ import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models'; import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad'; import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte'; import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { clasificacionHistologica } from './mapeo-histologico';
import { Dominio, requireDominio } from './indicadores.models'; import { Dominio, requireDominio } from './indicadores.models';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per // A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
@@ -96,10 +97,33 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) { || !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida'); throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
} }
const respuesta = v as unknown as SeguimientoTablaResponse; const respuesta = clasificarHistologia(v as unknown as SeguimientoTablaResponse);
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta; return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
} }
const TIPO_HISTOLOGICO = 'tipo_histologico';
const CLASIFICACION_HISTOLOGICA = 'clasificacion_histologica';
/**
* A list that carries the histologic type of each patient (`tipo_histologico`) also shows its classification, computed
* from that same value in the same row, in a column placed after the type's (or after the biopsy result when the type
* has no column). Rows without a type, and lists without the field, are left as received.
*/
export function clasificarHistologia(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
if (!r.items.some(item => typeof item[TIPO_HISTOLOGICO] === 'string') || r.columnas.some(c => c.clave === CLASIFICACION_HISTOLOGICA)) return r;
const columnas = [...r.columnas];
const despuesDe = [TIPO_HISTOLOGICO, 'biopsia'].map(k => columnas.findIndex(c => c.clave === k)).find(i => i >= 0) ?? columnas.length - 1;
columnas.splice(despuesDe + 1, 0, { clave: CLASIFICACION_HISTOLOGICA, etiqueta: 'Clasificación histológica' });
return {
...r,
columnas,
items: r.items.map(item => {
const tipo = item[TIPO_HISTOLOGICO];
return typeof tipo === 'string' ? { ...item, [CLASIFICACION_HISTOLOGICA]: clasificacionHistologica(tipo) } : item;
}),
};
}
/** /**
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is * A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays * rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays
@@ -11,7 +11,7 @@
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p> <p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
<div class="headline"> <div class="headline">
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span> <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: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</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> </div>
@for (dom of a.dominios; track dom.codigo) { @for (dom of a.dominios; track dom.codigo) {
<div class="dominio"> <div class="dominio">
@@ -37,39 +37,45 @@
</section> </section>
<section class="panel calidad" aria-label="Calidad del EEG"> <section class="panel calidad" aria-label="Calidad del EEG">
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3> <h3>Calidad del EEG</h3>
@if (d.eeg; as e) { @if (d.eeg; as e) {
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p> <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"> <div class="headline">
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span> <span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
<small>La calificación general es la peor de sus criterios.</small> <small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG, según las reglas siguientes.' }}</small>
</div> </div>
<dl> <dl>
@for (c of e.criterios_calidad; track c.codigo) { @for (c of delEstudio(e); track c.codigo) {
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd> <dt>{{ c.etiqueta }}@if (c.decisivo) {<small> (decisiva)</small>}</dt><dd [attr.data-calidad]="c.nivel">{{ valorDe(c) }}</dd>
} }
</dl> </dl>
@if (canalesMalos(e).length) {
<p class="efectos-titulo">Canales descartados</p>
<ul class="canales-malos">
@for (c of canalesMalos(e); track $index) { <li><strong>{{ c.electrodo }}</strong> · {{ c.etiqueta }}</li> }
</ul>
}
} @else { <p>Sin EEG registrado.</p> } } @else { <p>Sin EEG registrado.</p> }
</section> </section>
@if (d.eeg; as e) { @if (d.eeg; as e) {
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)"> <div class="alteraciones-zona" [class.abierta]="abierto(e)">
<section class="panel alteraciones" aria-label="Alteraciones del EEG"> <section class="panel alteraciones" aria-label="Alteraciones del EEG">
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3> <h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p> <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> } @if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
<ul class="metricas"> <ul class="metricas">
@for (m of e.alteraciones; track m.codigo) { @for (m of e.alteraciones; track m.codigo) {
<li [attr.data-estado]="m.estado"> <li [attr.data-estado]="m.estado">
<div class="metrica"> <div class="metrica">
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo" <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> [attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
<span class="estado">{{ estado[m.estado] }}</span> <span class="estado">{{ estado[m.estado] }}</span>
</div> </div>
@if (m.valor !== null) { @if (m.referencia; as r) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p> <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 { } @else {
<p class="valor">Sin registro de sueño en el estudio.</p> <p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
} }
@if (m.efectos.length) { @if (m.efectos.length) {
<p class="efectos-titulo">Posibles efectos asociados</p> <p class="efectos-titulo">Posibles efectos asociados</p>
@@ -82,8 +88,24 @@
</ul> </ul>
</section> </section>
@if (mapaActual(e); as mapa) { @if (abierto(e)) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas"> <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>
</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> <h3>Zonas más afectadas</h3>
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p> <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> <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>
@@ -96,9 +118,54 @@
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li> <li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
} }
</ol> </ol>
}
</section></div> </section></div>
} }
</div> </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>
<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>
@if (!filasRelacion(rel).length) {
<p class="sin-alteraciones">Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.</p>
} @else {
<div class="tabla-relacion" role="region" aria-label="Asociaciones por zona" tabindex="0">
<table>
<thead>
<tr>
<th scope="col">Zona del EEG</th><th scope="col">Aspecto del ADOS-2</th><th scope="col">Asociación en la cohorte</th>
<th scope="col">Probabilidad para este paciente</th><th scope="col">Lo que muestra su ADOS-2</th>
</tr>
</thead>
<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>{{ 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="prob">{{ porcentaje(f.probabilidad) }} %</span>
<span class="barra" aria-hidden="true">
<span class="paciente" [style.width.%]="porcentaje(f.probabilidad)"></span>
<span class="referencia" [style.left.%]="porcentaje(f.probabilidad_referencia)"></span>
</span>
<small>{{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} %</small>
</td>
<td>{{ observado(f) }}@if (coincide(f) !== null) { <small>{{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }}</small> }</td>
</tr>
}
</tbody>
</table>
</div>
<p class="nota">OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La
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 &lt; 0.05). Versión del modelo: {{ rel.version }}.</p>
}
</section>
}
</div> </div>
} }
@@ -1,4 +1,4 @@
:host { display: block; container-type: inline-size; } :host { display: block; container: host / inline-size; }
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; } .resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; }
.panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); } .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; } h3 { margin: 0 0 .15rem; font-size: 1rem; }
@@ -9,7 +9,7 @@ h3 { margin: 0 0 .15rem; font-size: 1rem; }
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; } border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.1rem; font-weight: 700; }
.css small { margin: 0; font-size: .7rem; font-weight: 400; } .css small { margin: 0; font-size: .7rem; font-weight: 400; }
.css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; } .css[data-nivel=alto], .css[data-calidad=malo] { border-color: #B3261E; color: #B3261E; }
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; } .css[data-nivel=moderado], .css[data-calidad=sin_analizar] { border-color: #B26A00; color: #B26A00; }
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); } .css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); }
.css[data-calidad] { flex: none; white-space: nowrap; } .css[data-calidad] { flex: none; white-space: nowrap; }
dd[data-calidad=malo] { color: #B3261E; } dd[data-calidad=malo] { color: #B3261E; }
@@ -23,7 +23,6 @@ button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outl
.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; } .leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; }
.leyenda-mapa .azul { background: #2166AC; } .leyenda-mapa .azul { background: #2166AC; }
.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; } .leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; }
dd[data-calidad=aceptable] { color: #B26A00; }
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; } .dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; }
.bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; } .bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
.bar span { display: block; height: 100%; background: var(--issste-text); } .bar span { display: block; height: 100%; background: var(--issste-text); }
@@ -56,7 +55,7 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
.mapa h3 { margin-top: 0; } .mapa h3 { margin-top: 0; }
@keyframes aparecer { from { opacity: 0; } } @keyframes aparecer { from { opacity: 0; } }
@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } } @container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } }
@container zona (max-width: 42rem) { .mapa { width: 100cqw; } } @container host (max-width: 42rem) { .mapa { width: 100cqw; } }
@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } } @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; } } @media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } }
.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; } .metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; }
@@ -72,3 +71,26 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; } .efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; } .efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; }
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; } button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
.canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; }
// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens.
.relacion { grid-column: 1 / -1; }
.tabla-relacion { overflow-x: auto; }
.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; }
.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; }
.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; }
.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; }
.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; }
.tabla-relacion .marca { color: #B3261E; font-weight: 600; }
.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; }
.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: 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); }
@@ -2,12 +2,17 @@ import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PlotlyFigure } from './indicadores.models'; import { PlotlyFigure } from './indicadores.models';
import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service'; import {
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
} from './tea-seguimiento.service';
// A zone counts as altered from |z| ≥ 2, as the alteration cards do.
const Z_ALTERADO = 2;
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
// ADOS-2 calibrated severity score ranges. // ADOS-2 calibrated severity score ranges.
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' }; const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Bueno', aceptable: 'Aceptable', malo: 'Malo' }; const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' };
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' }; const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
const INK = '#081839'; const INK = '#081839';
@@ -43,6 +48,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl
}; };
} }
// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point.
const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E';
export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse();
const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({
type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color,
line: { width: 0 }, name: nombre, hoverinfo: 'skip',
});
const unidad = m.unidad ? ` ${m.unidad}` : '';
const alterado = m.estado === 'aumentado' || m.estado === 'disminuido';
return {
data: [
banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'),
banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'),
{ type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 },
hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}<extra></extra>` },
{ type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente',
marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } },
hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})<extra></extra>` },
],
layout: {
margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK },
xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true },
yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true },
},
config: { displayModeBar: false },
};
}
@Component({ @Component({
selector: 'app-tea-paciente-resumen', selector: 'app-tea-paciente-resumen',
imports: [PlotlyChart], imports: [PlotlyChart],
@@ -56,7 +91,7 @@ export class TeaPacienteResumen implements OnInit {
readonly status = signal<'loading' | 'ready' | 'error'>('loading'); readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined); readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
figura?: PlotlyFigure; figura?: PlotlyFigure;
private mapaElegido?: string; mapaElegido?: string;
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef); private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
// The first solid background around this component: the map has no box of its own. // The first solid background around this component: the map has no box of its own.
private fondo() { private fondo() {
@@ -66,14 +101,30 @@ export class TeaPacienteResumen implements OnInit {
} }
return '#FFFFFF'; 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';
figuraNorma?: PlotlyFigure;
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); } mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
elegirMapa(eeg: TeaEeg, codigo: string) { // The age norm can only be drawn with the curve, the patient's value and their age.
// The chosen card closes the map again, and the cards take the whole space back. private conNorma(eeg: TeaEeg, codigo?: string) {
const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo); const m = eeg.alteraciones.find(a => a.codigo === codigo);
this.mapaElegido = mapa?.codigo; return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined;
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
} }
readonly clasificacion = CLASIFICACION; normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); }
abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); }
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);
}
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
readonly clasificacion = CLASIFICACIONES_ADOS2;
readonly nivelCss = NIVEL_CSS; readonly nivelCss = NIVEL_CSS;
readonly calidad = CALIDAD; readonly calidad = CALIDAD;
readonly estado = ESTADO; readonly estado = ESTADO;
@@ -82,15 +133,48 @@ export class TeaPacienteResumen implements OnInit {
this.status.set('loading'); this.status.set('loading');
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: d => { next: d => {
// Opens on the first altered metric, or on the first one if none is altered. // 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, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0]; const e = d.eeg;
this.mapaElegido = inicial?.codigo; if (e) {
this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined; 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'); this.detalle.set(d); this.status.set('ready');
}, },
error: () => this.status.set('error'), 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); }
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;
}
// Why a metric couldn't be evaluated, in the reader's terms.
sinEvaluar(m: TeaEegAlteracion) {
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'; }
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); } 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; } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
direccion(f: TeaRelacionAdos2) {
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)}`; }
observado(f: TeaRelacionAdos2) {
if (f.observado === null) return 'Sin dato';
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
return `CSS ${f.observado}`;
}
// Whether what the patient shows matches what the model leans to (above or below one half).
coincide(f: TeaRelacionAdos2) {
if (f.observado === null) return null;
const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8;
return presente === (f.probabilidad >= .5);
}
} }
@@ -1,13 +1,14 @@
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs'; import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir'; import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
import { estratoValor } from './indicadores-fhir'; import { estratoValor } from './indicadores-fhir';
import { SeguimientoQuery } from './cacu-seguimiento.models'; import { SeguimientoQuery } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service'; import { validSeguimientoQuery } from './cacu-seguimiento.service';
import { import {
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad,
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService, TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
} from './tea-seguimiento.service'; } from './tea-seguimiento.service';
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an // TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
@@ -19,15 +20,19 @@ interface Observation extends Resource {
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
interpretation?: Concept[]; dataAbsentReason?: Concept; interpretation?: Concept[]; dataAbsentReason?: Concept;
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[]; referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[]; component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueBoolean?: boolean; valueCodeableConcept?: Concept; extension?: Resource['extension'] }[];
} }
interface Report extends Resource { interface Report extends Resource {
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[]; effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
} }
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] } interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] }
const MAX_COUNT = 200; const MAX_COUNT = 200;
const METRICAS = 'tea-eeg-metrica'; const METRICAS = 'tea-eeg-metrica';
// The EEG analysis's quality checks, under the code system of its own validation report.
const CRITERIOS = 'urn:tea:validation';
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' }; 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.
@@ -77,10 +82,16 @@ export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Reco
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones }; return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
} }
// The module as the page writes it: `MODULO_1` is 1, the toddler module is T.
function moduloAdos2(codigo: string | undefined): string | undefined {
const modulo = codigo?.replace(/^ados2\.modulo\./, '');
return modulo === 'TODDLER' ? 'T' : modulo?.replace(/^MODULO_/, '');
}
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null { export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
const css = component(o, 'ados2.css')?.valueInteger; const css = component(o, 'ados2.css')?.valueInteger;
if (!o?.effectiveDateTime || typeof css !== 'number') return null; if (!o?.effectiveDateTime || typeof css !== 'number') return null;
const modulo = code(component(o, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '') ?? ''; const modulo = moduloAdos2(code(component(o, 'ados2.modulo')?.valueCodeableConcept)) ?? '';
const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase(); const clasificacion = code(component(o, 'ados2.clasificacion')?.valueCodeableConcept)?.replace('ados2.clasificacion.', '').toLowerCase();
const items = (o.component ?? []).filter(c => extension(c, 'dominio')); const items = (o.component ?? []).filter(c => extension(c, 'dominio'));
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => { const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
@@ -96,25 +107,56 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
return { return {
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '', fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0), dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
clasificacion: (clasificacion ?? 'no_espectro') as TeaAdos2['clasificacion'], css, clasificacion: clasificacion && Object.hasOwn(CLASIFICACIONES_ADOS2, clasificacion) ? clasificacion as TeaAdos2['clasificacion'] : null, css,
nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'], nivel_css: (RANGOS_CSS.find(r => css >= r.min && css <= r.max)?.codigo ?? 'minimo') as TeaAdos2['nivel_css'],
}; };
} }
// The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR
// extension holds scalars, not arrays.
function curvaDe(o: Observation): TeaCurvaReferencia | null {
const curva = extension(o, 'curva-referencia');
if (!curva) return null;
const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number');
return {
fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '',
edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'),
};
}
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
// cover the child's age (or none is in production yet).
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion { function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
const codigo = code(o.code) ?? ''; const codigo = code(o.code) ?? '';
const metrica = metricas.find(m => m.code === codigo); const metrica = metricas.find(m => m.code === codigo);
const evaluable = !o.dataAbsentReason && typeof o.valueQuantity?.value === 'number'; const valor = o.valueQuantity?.value ?? null;
const z = component(o, 'z')?.valueQuantity?.value;
const evaluable = valor !== null && typeof z === 'number';
const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable'; const estado = evaluable ? INTERPRETACION[code(o.interpretation?.[0]) ?? ''] ?? 'normal' : 'no_evaluable';
const range = o.referenceRange?.[0]; const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
const referencia = typeof low === 'number' && typeof high === 'number'
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
const curva = evaluable ? curvaDe(o) : null;
return { return {
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo, codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '', unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 }, referencia: evaluable ? referencia : null,
valor: evaluable ? o.valueQuantity!.value! : null, valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null, sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
estado,
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean), efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
...(curva ? { curva_referencia: curva } : {}),
};
}
// One quality check as the EEG analysis reports it: its value or reason, A/N, the bad channel's electrode, whether it
// alone invalidates the EEG.
function criterio(o: Observation): TeaCriterioCalidad {
const parte = (nombre: string) => o.component?.find(c => c.code?.text === nombre);
return {
codigo: codeIn(o.code, CRITERIOS)!, etiqueta: display(o.code) ?? codeIn(o.code, CRITERIOS)!,
valor: o.valueQuantity?.value ?? o.valueString ?? null, unidad: o.valueQuantity?.unit ?? '',
nivel: code(o.interpretation?.[0]) === 'A' ? 'malo' : 'bueno',
electrodo: parte('electrode')?.valueString ?? null, decisivo: parte('decisive')?.valueBoolean === true,
}; };
} }
@@ -123,8 +165,11 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
if (!report?.effectiveDateTime) return null; if (!report?.effectiveDateTime) return null;
const ids = new Set((report.result ?? []).map(r => referenceId(r))); const ids = new Set((report.result ?? []).map(r => referenceId(r)));
const listed = observations.filter(o => ids.has(o.id)); const listed = observations.filter(o => ids.has(o.id));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad; const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas)); const duracion = extension(report, 'duracion-min')?.valueDecimal;
const edad = extension(report, 'edad-meses')?.valueDecimal;
// The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards.
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas));
// A metric's electrode values are `electrodos-<the metric observation's id>`. // A metric's electrode values are `electrodos-<the metric observation's id>`.
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length))) const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
.map(o => { .map(o => {
@@ -135,19 +180,44 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable')); .filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
return { return {
fecha: report.effectiveDateTime.slice(0, 10), fecha: report.effectiveDateTime.slice(0, 10),
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0), duracion_min: duracion === undefined ? null : Math.round(duracion),
canales: extension(report, 'canales')?.valueInteger ?? 0, canales: extension(report, 'canales')?.valueInteger ?? null,
...(typeof edad === 'number' ? { edad_meses: edad } : {}),
calidad: calidad(report.conclusionCode?.[0]), calidad: calidad(report.conclusionCode?.[0]),
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({ criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
codigo: code(o.code)!.replace('eeg.calidad_', ''), etiqueta: display(o.code) ?? '',
valor: o.valueInteger ?? o.valueQuantity?.value ?? 0, unidad: typeof o.valueInteger === 'number' ? 'canales' : o.valueQuantity?.unit ?? '',
nivel: calidad(o.interpretation?.[0]),
})),
alteraciones, mapas, alteraciones, mapas,
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) }, ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
}; };
} }
// The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and
// probabilities. A row missing a number the panel needs is left out; without rows there is no panel.
export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null {
if (!riesgo) return null;
const nivel = extension(riesgo, 'modelo-nivel')?.valueString;
const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => {
const numero = (nombre: string) => extension(p, nombre)?.valueDecimal;
const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding;
const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString;
const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal,
numero('probabilidad-referencia')];
if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome)
|| !valores.every(v => typeof v === 'number')) return null;
const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[];
return {
biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z,
tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento,
or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null,
};
}).filter((f): f is TeaRelacionAdos2 => f !== null);
if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null;
return {
validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel,
n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0,
version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas,
};
}
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null { function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null; if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
return alteracionesDe(report, observations).length ? 'anormal' : 'normal'; return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
@@ -166,7 +236,7 @@ export function pacienteDeEpisodio(episode: Resource, included: Resource[], vali
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined; const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
const ados2 = byCode(observations, 'ados2'); const ados2 = byCode(observations, 'ados2');
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined; const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, ''); const modulo = moduloAdos2(code(component(ados2, 'ados2.modulo')?.valueCodeableConcept));
return { return {
id_seudonimo: id, id_seudonimo: id,
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code), grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
@@ -221,7 +291,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
const corte = query.corte ?? isoDay(this.today()); const corte = query.corte ?? isoDay(this.today());
const { desde, hasta } = ventana(corte, query.meses); const { desde, hasta } = ventana(corte, query.meses);
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta); let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
if (query.estatus) params = params.set('resultado-eeg', query.estatus); if (query.estatus) params = params.set('resultado-eeg', FILTRO_EEG[query.estatus] ?? query.estatus);
if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad)); if (query.grupo_edad) params = params.set('grupo-edad', grupoCodigo(query.grupo_edad));
const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css); const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css);
if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max); if (mchat) params = params.append('mchat', 'ge' + mchat.min).append('mchat', 'le' + mchat.max);
@@ -248,6 +318,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)), items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [], tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
resumen_eeg: { resumen_eeg: {
validadas, con_eeg_valido: validadas ? parameter(resumen, 'normales') + parameter(resumen, 'anormales') : parameter(resumen, 'con_eeg_valido'),
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'), normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
por_alteracion: porAlteracion(resumen, metricas), por_alteracion: porAlteracion(resumen, metricas),
}, },
@@ -261,14 +332,15 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
}).pipe(map(({ bundle, metricas }) => { }).pipe(map(({ bundle, metricas }) => {
const all = resources(bundle); const all = resources(bundle);
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[]; const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text); const episode = resources(bundle, 'EpisodeOfCare')[0];
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop(); const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
return teaPacienteDetalle({ return teaPacienteDetalle({
simulado: all.length > 0 && all.every(isSimulated), simulado: all.length > 0 && all.every(isSimulated),
id_seudonimo: id, id_seudonimo: id,
grupo_edad: grupoEdad(edad), grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
ados2: ados2DeObservacion(byCode(observations, 'ados2')), ados2: ados2DeObservacion(byCode(observations, 'ados2')),
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas), eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
...(relacion ? { relacion_ados2: relacion } : {}),
}, id); }, id);
})); }));
} }
@@ -4,7 +4,8 @@ import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service'; import { validSeguimientoQuery } from './cacu-seguimiento.service';
export type AlteracionesEeg = 'normal' | 'anormal'; // The EEG filter: by alteration once the domain expert has validated them, otherwise only by a valid EEG or none.
export type AlteracionesEeg = 'normal' | 'anormal' | 'valido' | 'sin_eeg_valido';
export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo'; export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo';
export interface TeaSeguimientoPaciente { export interface TeaSeguimientoPaciente {
id_seudonimo: string; id_seudonimo: string;
@@ -12,7 +13,7 @@ export interface TeaSeguimientoPaciente {
ultimo_eeg: string | null; ultimo_eeg: string | null;
mchat: number | null; mchat: number | null;
css_ados2: number | null; css_ados2: number | null;
alteraciones_eeg: AlteracionesEeg | null; alteraciones_eeg: 'normal' | 'anormal' | null;
modulo_ados2: string | null; modulo_ados2: string | null;
estado_caso: EstadoCaso; estado_caso: EstadoCaso;
// What a case in process still lacks. // What a case in process still lacks.
@@ -21,6 +22,9 @@ export interface TeaSeguimientoPaciente {
alteraciones: string[]; alteraciones: string[];
} }
export interface TeaResumenEeg { export interface TeaResumenEeg {
// Without validated alterations only the split by a valid EEG is known: `normales`, `anormales` and `por_alteracion`
// stay empty.
validadas: boolean; con_eeg_valido: number;
normales: number; anormales: number; sin_eeg: number; normales: number; anormales: number; sin_eeg: number;
por_alteracion: { codigo: string; etiqueta: string; n: number }[]; por_alteracion: { codigo: string; etiqueta: string; n: number }[];
} }
@@ -35,28 +39,60 @@ export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: nu
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] } export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
export interface TeaAdos2 { export interface TeaAdos2 {
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number; fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto'; clasificacion: ClasificacionAdos2 | null; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
} }
export type ClasificacionAdos2 = 'autismo' | 'espectro_autista' | 'no_espectro' | 'preocupacion_leve_moderada' | 'preocupacion_severa';
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number } export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review. // EEG metrics against age baselines and their associated effects, both pending medical validation.
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo'; export type TeaNivelCalidad = 'bueno' | 'malo' | 'sin_analizar';
// One quality check of the EEG analysis: a study-wide rule, or a bad channel with its electrode and reason.
export interface TeaCriterioCalidad {
codigo: string; etiqueta: string; valor: number | string | null; unidad: string; nivel: 'bueno' | 'malo';
electrodo: string | null; decisivo: boolean;
}
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable'; export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
export interface TeaEegAlteracion { export interface TeaEegAlteracion {
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number }; codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number; mediana: number | null } | null;
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[]; valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
// The age norm the reference comes from (percentiles by month), when the analysis sends it.
curva_referencia?: TeaCurvaReferencia | null;
}
export interface TeaCurvaReferencia {
fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[];
} }
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] } export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
export interface TeaEeg { export interface TeaEeg {
fecha: string; duracion_min: number; canales: number; fecha: string; duracion_min: number | null; canales: number | null;
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers. // Age at the EEG, to place the patient on the age norms.
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[]; edad_meses?: number | null;
// The overall rating is the EEG analysis's verdict; its checks say why.
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
alteraciones: TeaEegAlteracion[]; alteraciones: TeaEegAlteracion[];
// One map per alteration that could be evaluated, on shared axes. // One map per alteration that could be evaluated, on shared axes.
mapas: TeaEegMapa[]; mapas: TeaEegMapa[];
ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] }; ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] };
} }
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null } // The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for
// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation.
export interface TeaRelacionAdos2 {
biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number;
tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string;
or: number; ic_inf: number; ic_sup: number; q: number;
probabilidad: number; probabilidad_referencia: number; observado: number | null;
}
export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] }
export interface TeaPacienteDetalle {
simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null;
// Absent until the WebApi serves the model.
relacion_ados2?: TeaRelacionModelo | null;
}
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape. // TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
preocupacion_leve_moderada: 'Preocupación leve a moderada', preocupacion_severa: 'Preocupación de moderada a severa',
};
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' }; export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses']; export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary. // M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
@@ -71,15 +107,22 @@ export const RANGOS_CSS = [
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 }, { codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 }, { codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
]; ];
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }]; export const ALTERACIONES_EEG: SeguimientoStatus[] = [
{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' },
];
export const EEG_VALIDO: SeguimientoStatus[] = [{ codigo: 'valido', etiqueta: 'Con EEG válido' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' }];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v); const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal'; const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
const filtroEeg = (v: unknown) => v === null || ['normal', 'anormal', 'valido', 'sin_eeg_valido'].includes(v as string);
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max; const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
// ADOS-2 item codes: 0 to 3, and 7 to 9 for an item that doesn't apply or wasn't scored.
const CODIGOS_REACTIVO = [0, 1, 2, 3, 7, 8, 9];
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string'); const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
function validResumenEeg(r: unknown): boolean { function validResumenEeg(r: unknown): boolean {
return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion']) return record(r) && typeof r['validadas'] === 'boolean' && integer(r['con_eeg_valido'])
&& integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion'])
&& r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n'])); && r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n']));
} }
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse { export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
@@ -88,7 +131,7 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
const p = v['paginacion'], window = v['ventana'], filters = v['filtros']; const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10. // M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta']) if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(filters) || !eeg(filters['alteraciones_eeg']) || !record(filters) || !filtroEeg(filters['alteraciones_eeg'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages']) || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item) || !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string' && typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
@@ -106,33 +149,52 @@ const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
const text = (v: unknown) => typeof v === 'string' && v.length > 0; const text = (v: unknown) => typeof v === 'string' && v.length > 0;
function validAdos(a: unknown): boolean { function validAdos(a: unknown): boolean {
if (a === null) return true; if (a === null) return true;
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10) if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || typeof a['algoritmo'] !== 'string' || !score(a['css'], 1, 10)
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string) || !(a['clasificacion'] === null || Object.hasOwn(CLASIFICACIONES_ADOS2, a['clasificacion'] as string))
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false; || !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts. // Items carry an ADOS-2 code (algorithm 0–2); each domain and the total must be the sum of their parts.
const dominios = a['dominios'] as unknown[]; const dominios = a['dominios'] as unknown[];
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos']) const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2)) && d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && CODIGOS_REACTIVO.includes(r['puntaje'] as number) && score(r['puntaje_algoritmo'], 0, 2))
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0) && d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length); && d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0) return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0); && a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
} }
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered. // An age norm: ages in increasing order and, at each one, percentiles that never cross.
const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const;
function validCurva(c: unknown): boolean {
if (c === undefined || c === null) return true;
if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false;
const edades = c['edad_meses'] as unknown[], n = edades.length;
if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false;
const series = PERCENTILES.map(k => c[k]);
return series.every(s => Array.isArray(s) && s.length === n && s.every(finite))
&& edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i]));
}
// A metric that can't be evaluated says why and has no z; one that can has its value, z and reference.
function validAlteracion(a: unknown): boolean { function validAlteracion(a: unknown): boolean {
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia']) const ref = a !== null && record(a) ? a['referencia'] : undefined;
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number) if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false; || !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
&& (ref['mediana'] === null || finite(ref['mediana'])))
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false;
const estado = a['estado']; const estado = a['estado'];
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null; if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string); && (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
return finite(a['valor']) && finite(a['valor_z']) && ref !== null && a['sin_evaluar'] === null
&& ['normal', 'aumentado', 'disminuido'].includes(estado as string);
} }
function validEeg(e: unknown): boolean { function validEeg(e: unknown): boolean {
if (e === null) return true; if (e === null) return true;
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string); const optional = (v: unknown) => v === null || integer(v);
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad']) const edad = record(e) ? e['edad_meses'] : undefined;
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad']) if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false; || !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0)
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
&& (c['electrodo'] === null || text(c['electrodo'])) && (c['valor'] === null || finite(c['valor']) || text(c['valor'])))) return false;
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false; if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
const ejes = e['ejes_mapa']; const ejes = e['ejes_mapa'];
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false; if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
@@ -143,9 +205,21 @@ function validEeg(e: unknown): boolean {
&& m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) && m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v)))
&& Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))); && Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z'])));
} }
const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1;
function validRelacion(r: unknown): boolean {
if (r === undefined || r === null) return true;
return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string)
&& integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas'])
&& r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z'])
&& ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento'])
&& finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number)
&& probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia'])
&& (f['observado'] === null || finite(f['observado'])));
}
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle { export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])) if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])
|| !validRelacion(v['relacion_ados2']))
throw new Error('Resumen del paciente inválido'); throw new Error('Resumen del paciente inválido');
return v as unknown as TeaPacienteDetalle; return v as unknown as TeaPacienteDetalle;
} }
@@ -13,13 +13,14 @@ const data = {
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 }, paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }], items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }],
tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }], tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }],
resumen_eeg: { normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] }, resumen_eeg: { validadas: true, con_eeg_valido: 4, normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] },
}; };
const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) }); const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) });
const metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra }); const metrica = (codigo: string, etiqueta: string, extra: object) => ({
codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2, mediana: 1.5 }, efectos: [], sin_evaluar: null, ...extra });
const alteraciones = [ const alteraciones = [
metrica('ritmo_posterior', 'Ritmo posterior', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Ritmo más lento de lo esperado para la edad.'] }), metrica('ritmo_posterior', 'Ritmo posterior', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Ritmo más lento de lo esperado para la edad.'] }),
metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable' }), metrica('husos_sueno_n2', 'Husos de sueño N2', { valor: null, valor_z: null, estado: 'no_evaluable', referencia: null, sin_evaluar: 'sin_valor' }),
metrica('husos_sueno_n3', 'Husos de sueño N3', { valor: 1.4, valor_z: 0.2, estado: 'normal' }), metrica('husos_sueno_n3', 'Husos de sueño N3', { valor: 1.4, valor_z: 0.2, estado: 'normal' }),
metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }), metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }),
metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }), metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }),
@@ -30,8 +31,12 @@ const detalle = {
ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo', ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo',
dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] }, dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] },
{ codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] }, { codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] },
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable', eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'bueno',
criterios_calidad: [{ codigo: 'amplitud', etiqueta: 'Canales con amplitud extrema', valor: 1, unidad: 'canales', nivel: 'bueno' }, { codigo: 'linea', etiqueta: 'Ruido de la línea eléctrica', valor: 8, unidad: 'dB', nivel: 'aceptable' }], criterios_calidad: [
{ codigo: 'clean-windows', etiqueta: 'Ventanas limpias', valor: 95, unidad: '%', nivel: 'bueno', electrodo: null, decisivo: true },
{ codigo: 'line-noise', etiqueta: 'Ruido de la línea eléctrica', valor: 48, unidad: 'dB', nivel: 'malo', electrodo: null, decisivo: false },
{ codigo: 'dead-channel', etiqueta: 'Canal muerto', valor: 'dead channel', unidad: '', nivel: 'malo', electrodo: 'T3', decisivo: false },
],
alteraciones, alteraciones,
mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')], mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')],
ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } }, ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } },
@@ -75,7 +80,7 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('input[type=date]')).not.toBeNull(); expect(root.querySelector('input[type=date]')).not.toBeNull();
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!; const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG'); expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal']); expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal', 'Sin EEG válido']);
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 }; fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
fixture.componentInstance.apply(); fixture.componentInstance.apply();
const filtered = request(); const filtered = request();
@@ -167,6 +172,41 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('section.mapa')).not.toBeNull(); expect(root.querySelector('section.mapa')).not.toBeNull();
http.verify(); http.verify();
}); });
it('muestra la norma por edad con el paciente, con o sin 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 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');
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.
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(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[] }[];
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);
expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow();
http.verify();
});
it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => { it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => {
const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo); const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo);
const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor; const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;
@@ -218,7 +258,7 @@ describe('Seguimiento TEA', () => {
const panel = root.querySelector('#tea-detalle-T-0002')!; const panel = root.querySelector('#tea-detalle-T-0002')!;
expect(panel.textContent).toContain('CSS 3'); expect(panel.textContent).toContain('CSS 3');
expect(panel.textContent).toContain('Afecto social (AS)'); expect(panel.textContent).toContain('Afecto social (AS)');
expect(panel.textContent).toContain('Aceptable'); expect(panel.textContent).toContain('Válido');
// Opens with the map of the first altered metric. // Opens with the map of the first altered metric.
expect(panel.querySelector('app-plotly-chart')).not.toBeNull(); expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
// Item scores start collapsed. // Item scores start collapsed.
@@ -228,7 +268,7 @@ describe('Seguimiento TEA', () => {
expect(metricas.textContent).toContain('Disminuido'); expect(metricas.textContent).toContain('Disminuido');
expect(metricas.textContent).toContain('Posibles efectos asociados'); 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('Ritmo más lento de lo esperado para la edad.');
expect(metricas.textContent).toContain('Sin registro de sueño en el estudio.'); expect(metricas.textContent).toContain('No se pudo medir en el estudio.');
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual( 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']); ['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('Sin alteraciones en las métricas evaluadas.');
@@ -269,6 +309,29 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.'); expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
http.verify(); http.verify();
}); });
it('admite las clasificaciones del módulo T, una sin clasificar y los códigos de reactivo que no aplican', () => {
const ados2 = detalle.ados2;
for (const clasificacion of ['preocupacion_leve_moderada', 'preocupacion_severa', null]) {
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...ados2, clasificacion } }, 'T-0001')).not.toThrow();
}
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...ados2, clasificacion: 'dudoso' } }, 'T-0001')).toThrow();
const [as, crr] = ados2.dominios;
const noAplica = { ...ados2, dominios: [{ ...as, reactivos: [{ ...as.reactivos[0], puntaje: 8, puntaje_algoritmo: 2 }, as.reactivos[1]] }, crr] };
expect(() => teaPacienteDetalle({ ...detalle, ados2: noAplica }, 'T-0001')).not.toThrow();
});
it('sin alteraciones validadas resume y filtra solo por EEG válido', () => {
const fixture = open();
const sinValidar = { ...data, resumen_eeg: { validadas: false, con_eeg_valido: 2, normales: 0, anormales: 0, sin_eeg: 1, por_alteracion: [] } };
request().flush(sinValidar); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const resumen = root.querySelector('.resumen-eeg')!;
expect(Array.from(resumen.querySelectorAll('dt')).map(d => d.textContent)).toEqual(['Con EEG válido', 'Sin EEG válido']);
expect(Array.from(resumen.querySelectorAll('dd')).map(d => d.textContent)).toEqual(['2', '1']);
const opciones = Array.from(root.querySelectorAll<HTMLOptionElement>('select[name="estatus"] option')).map(o => o.textContent!.trim());
expect(opciones).toContain('Con EEG válido');
expect(opciones).not.toContain('Anormal');
http.verify();
});
it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => { it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => {
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow(); expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow(); expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
@@ -279,25 +342,27 @@ describe('Seguimiento TEA', () => {
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow(); expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow(); expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
}); });
it('la calidad general es una palabra, sus criterios son números y se validan', () => { it('la calidad es el veredicto del análisis, con sus reglas y los canales descartados, y se valida', () => {
const fixture = open(); const fixture = open();
request().flush(tres); fixture.detectChanges(); request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement; const root: HTMLElement = fixture.nativeElement;
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges(); root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
const panel = root.querySelector('section.calidad')!; const panel = root.querySelector('section.calidad')!;
expect(panel.querySelector('.css')!.textContent!.trim()).toBe('Aceptable'); const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim();
expect(Array.from(panel.querySelectorAll('dt, dd')).map(n => n.textContent)).toEqual(['Canales con amplitud extrema', '1 de 19', 'Ruido de la línea eléctrica', '8 dB']); expect(texto(panel.querySelector('.css')!)).toBe('Válido');
expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('aceptable'); expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']);
expect(panel.textContent).not.toMatch(/Impedancia|Artefactos|de 100/); expect(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('malo');
expect(Array.from(panel.querySelectorAll('.canales-malos li')).map(texto)).toEqual(['T3 · Canal muerto']);
const conCriterios = (criterios_calidad: unknown) => ({ ...detalle, eeg: { ...detalle.eeg, criterios_calidad } }); const conCriterios = (criterios_calidad: unknown) => ({ ...detalle, eeg: { ...detalle.eeg, criterios_calidad } });
expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow();
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: 'canales', nivel: 'bueno' }; const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: '', nivel: 'bueno', electrodo: null, decisivo: false };
expect(() => teaPacienteDetalle(conCriterios([criterio]), 'T-0001')).not.toThrow(); expect(() => teaPacienteDetalle(conCriterios([criterio, { ...criterio, valor: 'completo' }, { ...criterio, valor: null }]), 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, nivel: 'regular' }]), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, nivel: 'regular' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: null }]), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, decisivo: 'si' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: 20 }]), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, electrodo: '' }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'buena' } }, 'T-0001')).toThrow(); expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'buena' } }, 'T-0001')).toThrow();
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'sin_analizar', duracion_min: null, canales: null } }, 'T-0001')).not.toThrow();
http.verify(); http.verify();
}); });
it('valida las alteraciones del EEG', () => { it('valida las alteraciones del EEG', () => {
@@ -306,8 +371,35 @@ describe('Seguimiento TEA', () => {
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3, sin_evaluar: 'sin_referencia' }), 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], sin_evaluar: 'sin_valor' }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow(); expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
}); });
// 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,
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 } });
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle({ ...detalle, relacion_ados2: null }, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle(rel([fila]), 'T-0001')).not.toThrow();
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'));
expect(filas.length).toBe(1);
expect(filas[0].classList.contains('alterada')).toBe(true);
expect(filas[0].textContent).toContain('q < 0.001');
expect(filas[0].textContent).toContain('93 %');
http.verify();
});
}); });
@@ -1,7 +1,7 @@
<section class="dashboard"> <section class="dashboard">
<header><span class="domain">Trastorno del espectro autista, investigación</span><h1>Indicadores</h1><p>Explore la información del tamizaje.</p></header> <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">TEA</a></nav> <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 TEA"> <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() === '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() === '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() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
@@ -61,7 +61,7 @@
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> } @if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
@if (patientState() === 'listo') { @if (patientState() === 'listo') {
<article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article> <article class="card"><h3>ADOS-2</h3>@if (ados(); as ados) { <p>Fecha: {{ ados.effectiveDateTime }}</p><dl>@for (c of ados.component; track $index) { <div><dt>{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}</dt><dd>{{ componentValue(c) }}</dd></div> }</dl> } @else { <p>Sin información de ADOS-2.</p> }</article>
<article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article> <article class="card"><h3>EEG del estudio</h3>@if (eeg(); as eeg) { <p>Fecha: {{ eeg.effectiveDateTime }}</p><p>Calidad: {{ eegQuality() }}</p><p>Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.</p>@if (eeg.conclusion) { <p>{{ eeg.conclusion }}</p> }<dl>@for (o of quality(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}@if (electrode(o); as e) { · {{ e }} }</dt><dd>{{ observationValue(o) }} ({{ qualityStatus(o) }})</dd></div> }</dl> } @else { <p>Sin información de EEG.</p> }</article>
@if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> } @if (alterationsAvailable() && alterations().length) { <article class="card"><h3>Métricas del EEG</h3><dl>@for (o of alterations(); track o.id) { <div><dt>{{ o.code.coding?.[0]?.display }}</dt><dd>{{ observationValue(o) }}</dd></div> }</dl></article> }
} }
</section> </section>
@@ -1,5 +1,4 @@
.dashboard { max-width: 1200px; margin: 0 auto; padding: 1.5rem; color: #142b3d; } .dashboard { max-width: 1200px; margin: 0 auto; padding: 1.5rem; color: #142b3d; }
.domain { color: #24735a; font-weight: 600; }
.domain-nav, .tabs, form, .paging { display: flex; flex-wrap: wrap; gap: .8rem; align-items: end; margin: 1rem 0; } .domain-nav, .tabs, form, .paging { display: flex; flex-wrap: wrap; gap: .8rem; align-items: end; margin: 1rem 0; }
.domain-nav a { color: #216b56; padding: .5rem; } .domain-nav a { color: #216b56; padding: .5rem; }
.tabs { border-bottom: 1px solid #c9d6d1; } .tabs { border-bottom: 1px solid #c9d6d1; }
@@ -174,12 +174,14 @@ export class TeaStatusPage implements OnDestroy {
} }
ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); } ados() { return this.patientResources().find(r => r.resourceType === 'Observation' && code(r.code) === 'ados2'); }
eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); } eeg() { return this.patientResources().find(r => r.resourceType === 'DiagnosticReport' && code(r.code) === 'eeg'); }
eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : 'Sin dato'; } eegQuality() { const quality = code(this.eeg()?.conclusionCode?.[0]); return quality === 'BUENO' ? 'Buena' : quality === 'MALO' ? 'Mala' : quality === 'SIN_ANALIZAR' ? 'Sin analizar' : 'Sin dato'; }
eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; } eegExtension(name: string) { const e = this.eeg()?.extension?.find((x: Resource) => x.url.endsWith(`/${name}`)); return e?.valueDecimal ?? e?.valueInteger ?? 'Sin dato'; }
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : 'sin dato'; } // The EEG analysis's checks: A is out of range, N within.
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && code(r.code).startsWith('eeg.calidad_')); } qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'N' ? 'dentro de rango' : value === 'A' ? 'fuera de rango' : 'sin dato'; }
quality() { const ids = new Set((this.eeg()?.result ?? []).map((r: Resource) => r.reference)); return this.patientResources().filter(r => r.resourceType === 'Observation' && ids.has(`Observation/${r.id}`) && r.code?.coding?.[0]?.system === 'urn:tea:validation'); }
electrode(o: Resource): string | undefined { return o.component?.find((c: Resource) => c.code?.text === 'electrode')?.valueString; }
alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); } alterationsAvailable() { return this.measures().some(m => m.id.startsWith('M30-')); }
alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); } alterations() { return this.patientResources().filter(r => r.resourceType === 'Observation' && r.code?.coding?.[0]?.system?.endsWith('/tea-eeg-metrica') && !r.id?.startsWith('electrodos-')); }
componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); } componentValue(c: Resource) { return c.valueInteger ?? c.valueString ?? (text(c.valueCodeableConcept) || 'Sin dato'); }
observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}` : 'Sin dato'); } observationValue(o: Resource) { return o.valueInteger ?? (o.valueQuantity ? `${o.valueQuantity.value} ${o.valueQuantity.unit ?? ''}`.trim() : o.valueString ?? 'Sin dato'); }
} }
+1
View File
@@ -43,6 +43,7 @@
--issste-space-2: var(--space-2); --issste-space-2: var(--space-2);
--issste-space-3: var(--space-3); --issste-space-3: var(--space-3);
--issste-space-4: var(--space-4); --issste-space-4: var(--space-4);
--issste-space-5: var(--space-5);
--issste-space-6: var(--space-6); --issste-space-6: var(--space-6);
--issste-radius: var(--mat-sys-corner-medium); --issste-radius: var(--mat-sys-corner-medium);
} }