Compare commits

..

15 Commits

Author SHA1 Message Date
ulises 4c181af291 CaMa patient card: the recurrence figure of the scenarios the patient meets, and a menu of both cohorts' scenarios
Shown only for patients after treatment, in the recurrence slot of "Pronóstico y recomendaciones". Includes the survival
figure this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:39 -06:00
edgar 7d180417d8 Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:11 -06:00
edgar 00f773dd75 CaCu patient record reads the patient's FHIR RiskAssessment
The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> and validates the searchset Bundle at the
boundary (simulado tag, the patient asked for, one index date, probabilities and intervals); it shows the model, the
risk's index date, the outcome, the evaluation and one row per horizon from each prediction's whenPeriod. The cohort's
definition and the PIMM variables are no longer shown; an empty Bundle is a patient without a confirmed risk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:11:56 -06:00
edgar 3bb1c8dd84 CaCu patient record shows the risk's index date
The record's index date is riesgo.fecha_indice (the model's decision point the horizons count from), not the cohort
member's; the field is optional in the contract and validated as an ISO date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:48 -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
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
AlbertoPMDM 04795a09cc feat(tea): read the EEG analysis's verdict, quality checks and age baselines 2026-11-19 15:43:27 -06:00
89 changed files with 1686 additions and 939 deletions
-27
View File
@@ -14,30 +14,3 @@ npx ng build # compilación de producción en dist/WebApp
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
## Fuente de histopatología BI-RADS
La compilación estándar incorpora la fuente sintética de la tarjeta de
histopatología en **CaMa → Resumen**. La dona y las barras usan el mismo
fixture. El catálogo, los filtros generales y los demás indicadores siguen
usando WebApi. Si el catálogo carga sin la medida de histopatología, Resumen
incluye la tarjeta con su fuente local.
El archivo
`src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json`
contiene conteos inventados, sin validez clínica. Define los 12 subtipos en orden
con sus identificadores y colores. Cada mes remite a un perfil de conteos por
estrato BI-RADS que incluye resultados benignos, subtipos, casos sin biopsia
reportada y casos sin dato. Abarca enero de 2025 a diciembre de 2026. Los semestres
suman esos mismos meses. Un periodo fuera de cobertura queda sin resultados.
El anillo interior usa el total con resultado de biopsia. El exterior reparte
el grupo «Riesgo a carcinoma» entre sus 12 subtipos. Las barras y el centro
muestran el subconjunto elegido sobre el total con resultado, por BI-RADS y del
periodo completo, respectivamente. La leyenda permite elegir subtipos incluso
cuando el sector es demasiado pequeño.
Cuando se valide la matriz clínica de subtipos, el adaptador FHIR podrá construir
el mismo modelo de presentación con los conteos, estratos, denominadores y
reglas de supresión aprobados. Los componentes de visualización ya consumen
ese modelo tanto para las tasas como para los anillos.
+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)]);
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);
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
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 () => {
await ir('/indicadores/cama');
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(selector()!.getAttribute('aria-expanded')).toBe('true');
});
@@ -69,7 +69,7 @@ describe('Encabezado del marco', () => {
const items = await abrirMenu();
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
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.
const ubicacion = TestBed.inject(Location);
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
+29 -6
View File
@@ -117,7 +117,8 @@
.domain-selector--espera {
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. */
@@ -160,9 +161,31 @@
width: 18px;
}
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
@media (max-width: 599px) {
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
.app-shell--indicadores .brand { margin-inline-end: auto; }
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
// Full domain names need their own track. On a wide header they sit beside the title;
// below 900px the name takes a row of its own so the logo and the exit stay together.
.app-shell--indicadores .site-header__content {
display: grid;
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 () => {
const page = await render('/indicadores/cacu');
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 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(
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. */
@@ -13,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
import { ImportFlow } from '../domain/import-flow';
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: '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; }
.domain-selector {
flex: 0 0 auto;
max-width: 100%;
height: auto;
min-height: 40px;
background-color: var(--issste-accent);
color: var(--issste-text);
font-weight: 700;
line-height: 1.2;
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:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
+2 -2
View File
@@ -30,9 +30,9 @@ export function code(concept: Concept | undefined): string | undefined {
export function display(concept: Concept | undefined): string | undefined {
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 {
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;
}
// The extensions named `name` (the last segment of their URL).
@@ -1,41 +0,0 @@
{
"origen": "Sintético (WebApp). Conteos inventados para demostrar la visualización; sin significado clínico.",
"categorias": [
{ "id": "DUCTAL_NST", "etiqueta": "Ductal (NST)", "color": "#AD386D" },
{ "id": "LOBULILLAR", "etiqueta": "Lobulillar", "color": "#5C55BB" },
{ "id": "OTROS", "etiqueta": "Otros", "color": "#007F86" },
{ "id": "DUCTAL_LOBULILLAR", "etiqueta": "Ductal-lobulillar mixto", "color": "#8767C9" },
{ "id": "MUCINOSO", "etiqueta": "Mucinoso", "color": "#3274BF" },
{ "id": "PAGET", "etiqueta": "Paget", "color": "#D35C91" },
{ "id": "PAPILAR", "etiqueta": "Papilar", "color": "#537723" },
{ "id": "TUBULAR_CRIBIFORME", "etiqueta": "Tubular / cribiforme", "color": "#9454AA" },
{ "id": "MICROPAPILAR", "etiqueta": "Micropapilar", "color": "#C24938" },
{ "id": "SIN_MAPEAR", "etiqueta": "SIN MAPEAR", "color": "#68778B" },
{ "id": "INFLAMATORIO", "etiqueta": "Inflamatorio", "color": "#A4932A" },
{ "id": "MEDULAR", "etiqueta": "Medular", "color": "#438573" }
],
"meses": {
"2025-01": "A", "2025-02": "B", "2025-03": "A", "2025-04": "B", "2025-05": "B", "2025-06": "A",
"2025-07": "B", "2025-08": "A", "2025-09": "B", "2025-10": "A", "2025-11": "B", "2025-12": "B",
"2026-01": "A", "2026-02": "B", "2026-03": "A", "2026-04": "A", "2026-05": "B", "2026-06": "A",
"2026-07": "A", "2026-08": "B", "2026-09": "B", "2026-10": "B", "2026-11": "A", "2026-12": "B"
},
"perfiles": {
"A": {
"BIRADS_4": { "benignos": 54, "subtipos": [8, 3, 2, 1, 1, 0, 1, 0, 0, 1, 0, 0], "sinBiopsia": 5, "sinDato": 1 },
"BIRADS_4A": { "benignos": 93, "subtipos": [5, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0], "sinBiopsia": 9, "sinDato": 2 },
"BIRADS_4B": { "benignos": 67, "subtipos": [19, 5, 3, 2, 1, 1, 1, 1, 0, 1, 0, 1], "sinBiopsia": 6, "sinDato": 2 },
"BIRADS_4C": { "benignos": 30, "subtipos": [33, 9, 5, 4, 3, 1, 2, 2, 1, 2, 1, 1], "sinBiopsia": 4, "sinDato": 1 },
"BIRADS_5": { "benignos": 10, "subtipos": [48, 12, 8, 6, 4, 3, 3, 2, 2, 2, 2, 1], "sinBiopsia": 3, "sinDato": 1 },
"BIRADS_6": { "benignos": 0, "subtipos": [15, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0], "sinBiopsia": 0, "sinDato": 1 }
},
"B": {
"BIRADS_4": { "benignos": 49, "subtipos": [7, 2, 2, 1, 0, 0, 1, 0, 0, 2, 0, 1], "sinBiopsia": 6, "sinDato": 2 },
"BIRADS_4A": { "benignos": 86, "subtipos": [6, 2, 0, 1, 0, 0, 1, 1, 0, 2, 0, 0], "sinBiopsia": 7, "sinDato": 1 },
"BIRADS_4B": { "benignos": 66, "subtipos": [15, 4, 4, 2, 2, 0, 1, 1, 1, 1, 0, 0], "sinBiopsia": 4, "sinDato": 1 },
"BIRADS_4C": { "benignos": 35, "subtipos": [31, 8, 5, 3, 2, 1, 3, 2, 1, 1, 1, 1], "sinBiopsia": 5, "sinDato": 2 },
"BIRADS_5": { "benignos": 9, "subtipos": [44, 14, 7, 7, 5, 4, 3, 2, 2, 1, 2, 1], "sinBiopsia": 2, "sinDato": 2 },
"BIRADS_6": { "benignos": 0, "subtipos": [17, 5, 3, 1, 2, 1, 0, 1, 1, 2, 1, 1], "sinBiopsia": 0, "sinDato": 0 }
}
}
}
@@ -1,136 +0,0 @@
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
import { recolorFigure } from './indicadores-c2-palette';
import { categoriasExteriores, donaHistopatologia, figuraTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama';
import { IndicadoresMemory } from './indicadores-memory';
import { IndicadoresPage } from './indicadores-page';
const nombres = [
'Ductal (NST)', 'Lobulillar', 'Otros', 'Ductal-lobulillar mixto', 'Mucinoso', 'Paget', 'Papilar',
'Tubular / cribiforme', 'Micropapilar', 'SIN MAPEAR', 'Inflamatorio', 'Medular',
];
const [modelo] = modelosHistopatologiaDemo('mes', ['2025-02']);
const suma = (valores: number[]) => valores.reduce((a, b) => a + b, 0);
describe('Fuente sintética de histopatología CaMa', () => {
it('dibuja los 12 subtipos en orden, con colores distintos y con el subtotal del grupo exterior', () => {
const seleccion = seleccionBase(modelo);
const [, interior, exterior] = recolorFigure(donaHistopatologia(modelo, seleccion, 'claro')).data;
expect(exterior['labels']).toEqual(nombres);
expect(categoriasExteriores(modelo).map(c => c.etiqueta)).toEqual(nombres);
const colores = categoriasExteriores(modelo).map(c => c.color);
expect(new Set(colores).size).toBe(12);
expect(exterior['marker']).toMatchObject({ colors: colores });
expect(interior['labels']).toEqual(['No maligno', 'Riesgo a carcinoma']);
expect(suma(exterior['values'] as number[])).toBe((interior['values'] as number[])[1]);
expect(suma(interior['values'] as number[])).toBe(modelo.conResultado);
expect((exterior['values'] as number[]).every(n => n > 0)).toBe(true);
});
it('mantiene SIN MAPEAR en mayúsculas y evita porcentajes indefinidos en un anillo sin casos', () => {
const figura = figuraTasas(modelo, { grupo: modelo.base, categoria: 'SIN_MAPEAR' }, 'claro');
expect(figura.layout['xaxis']).toMatchObject({ title: { text: 'Porcentaje con SIN MAPEAR' } });
const benignos = modelo.totales['BENIGNO'];
const totales = { ...modelo.totales, ...Object.fromEntries(categoriasExteriores(modelo).map(c => [c.id, 0])) };
const sinCasos = { ...modelo, totales, conResultado: benignos };
const exterior = donaHistopatologia(sinCasos, seleccionBase(sinCasos), 'claro').data[2];
expect(exterior['customdata']).toEqual(nombres.map(() => ['0', '—']));
});
it('reconcilia barras, anillos y tabla para cada selección, incluidos los ceros', () => {
for (const { id, grupo } of modelo.categorias) {
const seleccion = { grupo, categoria: id };
const valores = tasas(modelo, seleccion);
expect(suma(valores.map(t => t.k!))).toBe(modelo.totales[id]);
for (const { fila, k, valor, bajo, alto } of valores) {
expect(k).toBe(fila.celdas[id].n);
expect(valor).toBe(100 * k! / fila.den!);
expect(bajo).toBeGreaterThanOrEqual(0);
expect(alto).toBeLessThanOrEqual(100);
expect(fila.total.n).toBe(fila.den! + fila.aparte['SIN_BIOPSIA'].n! + fila.aparte['SIN_DATO'].n!);
}
const [barra] = figuraTasas(modelo, seleccion, 'oscuro', true).data;
expect(barra['type']).toBe('bar');
expect(barra['x']).toEqual(valores.map(t => t.valor));
}
expect(tasas(modelo, { grupo: modelo.base, categoria: 'MICROPAPILAR' })[0].valor).toBe(0);
});
it('agrega los mismos meses en cada semestre y devuelve vacío fuera de cobertura', () => {
const semestres = modelosHistopatologiaDemo('semestre');
expect(semestres.map(m => m.periodo)).toEqual(['2025-S1', '2025-S2', '2026-S1', '2026-S2']);
const primerSemestre = modelosHistopatologiaDemo('mes').filter(m => m.periodo <= '2025-06');
for (const { id } of modelo.categorias) {
expect(semestres[0].totales[id]).toBe(suma(primerSemestre.map(m => m.totales[id]!)));
}
expect(modelosHistopatologiaDemo('mes', ['2025-03', '2025-02']).map(m => m.periodo)).toEqual(['2025-03', '2025-02']);
expect(modelosHistopatologiaDemo('mes', ['2024-10'])).toEqual([]);
});
it.each([true, false])('Resumen usa los datos incorporados con medida publicada = %s', publicada => {
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [
provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
{ provide: PLOTLY_LOADER, useValue: () => new Promise(() => {}) },
] });
const http = TestBed.inject(HttpTestingController);
const memory = TestBed.inject(IndicadoresMemory);
for (const dominio of ['cama', 'cacu', 'tea'] as const) memory.finishInitialKpiPresentation(dominio);
const f = TestBed.createComponent(IndicadoresPage);
const catalogo = (id: string) => [{ id, titulo: 'Indicador publicado', contrato: 'C2', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
http.expectOne('/tea/indicadores').flush(catalogo('tea_prueba'));
f.componentInstance.changeDominio('cama');
const idsCama = ['cama_birads_456_mastografia', 'cama_birads_456_paciente'];
if (publicada) idsCama.push('cama_histopatologia_birads');
http.expectOne('/cama/indicadores').flush(idsCama.flatMap(catalogo));
f.detectChanges();
const tarjeta = f.debugElement.query(node => node.componentInstance instanceof IndicadorHistopatologiaCama);
expect(tarjeta).toBeTruthy();
const histo = tarjeta.componentInstance as IndicadorHistopatologiaCama;
const card = f.debugElement.queryAll(By.directive(IndicadorCatalogCard))
.map(node => node.componentInstance as IndicadorCatalogCard)
.find(item => item.indicador.id === 'cama_histopatologia_birads')!;
card.setVisible(true);
f.detectChanges();
expect(histo.status()).toBe('ready');
expect(histo.contextPeriod).toBe('2026-S2');
expect(f.nativeElement.textContent).toContain('Tiempo de diagnóstico a tratamiento');
expect(f.componentInstance.catalog().map(item => item.id)).toEqual(idsCama);
expect(f.nativeElement.querySelector('app-indicador-conteos-pareados')).not.toBeNull();
expect([...tarjeta.nativeElement.querySelectorAll('.child')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(nombres);
expect(histo.selectionLabel).toBe('Riesgo a carcinoma');
histo.plotClicked({ points: [{ data: { name: 'categorias' }, pointNumber: 9 }] });
f.detectChanges();
expect(histo.selectionLabel).toBe('SIN MAPEAR');
expect(histo.ratesFigure!.data[0]['x']).toEqual(tasas(histo.model!, histo.selection!).map(t => t.valor));
expect(tarjeta.nativeElement.querySelector('.child[aria-pressed=true]').textContent.trim()).toBe('SIN MAPEAR');
histo.plotClicked({ points: [{ data: { name: 'grupos' }, pointNumber: 0 }] });
expect(histo.selectionLabel).toBe('No maligno');
histo.plotClicked({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] });
expect(histo.selectionLabel).toBe('Riesgo a carcinoma');
histo.changePeriod(-1);
expect(histo.contextPeriod).toBe('2026-S1');
histo.showHelp();
f.detectChanges();
expect(tarjeta.nativeElement.querySelector('.methodology').textContent).toContain('El exterior muestra solo la distribución de los subtipos');
http.expectNone(req => /cama_histopatologia_birads\/(datos|metadatos)$/.test(req.url));
for (const dominio of ['cacu', 'tea'] as const) {
f.componentInstance.changeDominio(dominio);
http.expectOne('/' + dominio + '/indicadores').flush(catalogo(dominio + '_prueba'));
f.detectChanges();
expect(f.nativeElement.querySelector('app-indicador-histopatologia-cama')).toBeNull();
expect(f.nativeElement.querySelector('.catalog-grid').textContent).toContain('Indicador publicado');
}
f.destroy();
http.match(() => true);
http.verify();
});
});
@@ -1,53 +0,0 @@
import fixture from './fixtures/cama_histopatologia_birads_demo_sintetica.json';
import { C2_PALETTE } from './indicadores-c2-palette';
import { Celda } from './indicadores-confirmacion-citologia';
import {
APARTE, ESTRATOS_BIRADS, ETIQUETA_ESTRATO, FilaBirads, ModeloHistopatologia,
} from './indicadores-histopatologia-cama';
import { TipoPeriodo } from './indicadores.models';
const RIESGO = 'RIESGO_CARCINOMA';
const NO_MALIGNO = 'NO_MALIGNO';
const BENIGNO = 'BENIGNO';
const subtipos = fixture.categorias.map(c => ({ ...c, grupo: RIESGO }));
const categorias = [
...subtipos,
{ id: BENIGNO, etiqueta: 'Benigno', color: C2_PALETTE.frios[0], grupo: NO_MALIGNO },
];
const grupos = [
{ id: NO_MALIGNO, etiqueta: 'No maligno', color: C2_PALETTE.frios[3], categorias: [BENIGNO] },
{ id: RIESGO, etiqueta: 'Riesgo a carcinoma', color: C2_PALETTE.calidos[0], categorias: subtipos.map(c => c.id) },
];
const meses = Object.entries(fixture.meses).map(([mes, perfil]) => ({
mes,
semestre: mes.slice(0, 4) + (mes.slice(5) <= '06' ? '-S1' : '-S2'),
perfil: fixture.perfiles[perfil as keyof typeof fixture.perfiles],
}));
const sumar = (valores: number[]) => valores.reduce((total, n) => total + n, 0);
const publicada = (n: number) => ({ n, estado: 'Publicado' as const });
export function modelosHistopatologiaDemo(tipo: TipoPeriodo, solicitados?: readonly string[]): ModeloHistopatologia[] {
const disponibles = [...new Set(meses.map(mes => mes[tipo]))].sort();
const periodos = solicitados ? solicitados.filter(p => disponibles.includes(p)) : disponibles;
return periodos.map(periodo => {
const enPeriodo = meses.filter(mes => mes[tipo] === periodo);
const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => {
const datos = enPeriodo.map(mes => mes.perfil[id]);
const celdas: Record<string, Celda> = Object.fromEntries(subtipos.map((subtipo, i) =>
[subtipo.id, publicada(sumar(datos.map(d => d.subtipos[i])))]
));
celdas[BENIGNO] = publicada(sumar(datos.map(d => d.benignos)));
const den = sumar(Object.values(celdas).map(celda => celda.n!));
const sinBiopsia = sumar(datos.map(d => d.sinBiopsia));
const sinDato = sumar(datos.map(d => d.sinDato));
return { id, etiqueta: ETIQUETA_ESTRATO[id], celdas, den, estado: 'Publicado',
aparte: { SIN_BIOPSIA: publicada(sinBiopsia), SIN_DATO: publicada(sinDato) },
total: publicada(den + sinBiopsia + sinDato) };
});
const totales = Object.fromEntries(categorias.map(c => [c.id, sumar(filas.map(fila => fila.celdas[c.id].n!))]));
return { periodo, categorias, grupos, base: RIESGO, filas, totales,
conResultado: sumar(Object.values(totales)), aparte: [...APARTE], vacio: false, notas: [],
grupoAnilloExterior: RIESGO };
});
}
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
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.
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
@@ -56,7 +56,7 @@ import { parConteos } from './indicadores-conteos-pareados';
</div>
} @else if (isHistopatologia) {
<div #visibilityRegion class="confirmacion-region">
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (tiempos; as par) {
<div #visibilityRegion class="tiempos-region">
@@ -135,8 +135,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
});
}
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
get sobrio() { return this.dominio === 'cama'; }
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
get sobrio() { return true; }
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
@@ -7,7 +7,7 @@
@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) {
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo;
@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) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
@@ -8,20 +8,27 @@
<button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
@if (helpOpen) {
<div class="methodology" id="histo-como-leer" role="tooltip">
<p>Cada barra muestra el porcentaje de pacientes con resultado de biopsia en la categoría BI-RADS que corresponde a la selección. La línea indica el intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» se muestran aparte en la tabla.</p>
<p>El anillo interior compara los grupos entre todas las pacientes con resultado. El exterior muestra solo la distribución de los subtipos dentro de «Riesgo a carcinoma». Selecciona un sector o su etiqueta para actualizar las barras.</p>
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@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> }
</section>
}
}
</div>
}
</div>
</div>
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('incompatible') { <p role="alert">{{ message }}</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@case ('error') { <div role="alert"><p>{{ 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() === 'empty') {
<p role="status">No hay resultados de biopsia para el periodo seleccionado.</p>
}
@if (status() === 'ready') {
@if (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
@@ -30,6 +37,8 @@
</nav>
}
@if (model; as m) {
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend">
<div class="tab-bar">
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
@@ -41,7 +50,7 @@
<div class="child-groups">
@for (g of m.grupos; track g.id) {
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id">
@for (c of categoriasExteriores(m); track c.id; let ci = $index) {
@for (c of m.categorias; track c.id; let ci = $index) {
@if (c.grupo === g.id) {
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
@@ -62,8 +71,9 @@
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Ver valores</summary>
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
@@ -1,15 +1,28 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { snapshotKey } from './indicadores-snapshots';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { Celda } from './indicadores-confirmacion-citologia';
import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA,
ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama';
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
// Figures of the kit whose "Cómo leer" describes this coordinated view.
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
/**
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
*/
@Component({
selector: 'app-indicador-histopatologia-cama',
imports: [PlotlyChart],
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-histopatologia-cama.html',
styleUrl: './indicador-confirmacion-citologia.scss',
})
@@ -19,7 +32,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred');
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
selection?: SeleccionHistopatologia;
periods: string[] = [];
@@ -28,9 +43,10 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure;
helpOpen = false;
readonly categoriasExteriores = categoriasExteriores;
private helpPinned = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
private pages: ModeloHistopatologia[] = [];
@@ -45,8 +61,21 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : '');
}
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
readonly estadoTasa = estadoTasa;
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
get readingGuide() {
const details = this.metadata?.figuras_detalle ?? [];
return FIGURAS.flatMap(([figura, nombre]) => {
const detail = details.find(item => item.figura === figura);
const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
toggleHelp() {
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
this.helpPinned = true;
@@ -55,6 +84,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
showHelp() {
if (this.helpOpen) return;
this.helpOpen = true;
this.metadataRequested.emit();
}
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
onHelpFocusOut(event: FocusEvent) {
@@ -65,32 +95,53 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
}
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied)
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]);
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
if (key !== this.key) {
this.key = key; this.loaded = false;
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
this.clear();
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
}
retry() { if (this.visible) this.load(); }
private clear() {
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
this.donutFigure = undefined; this.ratesFigure = undefined;
}
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return;
}
const { tipo, selection } = this.applied;
this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined);
this.periods = this.pages.map(modelo => modelo.periodo);
this.periodIndex = Math.max(0, this.periods.length - 1);
this.activatePeriod();
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
{ estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
next: datos => {
if (key !== this.key) return;
try {
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
// The most recent period first; navigation goes back.
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.clear();
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error);
this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
this.changeDetector.markForCheck();
}
private activatePeriod() {
this.model = this.pages[this.periodIndex];
@@ -115,5 +166,5 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
}
@@ -0,0 +1,48 @@
import { Component, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
/**
* CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator
* (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number.
*/
@Component({
selector: 'app-indicador-histopatologia-pendiente',
host: { class: 'dual-card' },
imports: [MatButtonModule, MatCardModule],
template: `
<mat-card>
<h2>Resultado histopatológico por categoría BI-RADS</h2>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
@if (ayuda()) {
<div class="methodology">
<p>Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.</p>
</div>
}
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
<div class="figures">
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
</div>
</mat-card>
`,
styles: `
:host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; }
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.estado { color: var(--issste-text-secondary); }
.methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.methodology p { margin: 0; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); }
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
`,
})
export class IndicadorHistopatologiaPendiente {
readonly ayuda = signal(false);
}
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
}
<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="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; }
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; }
// CaMa's cards are as tall as their grid row.
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section) .value { font-size: 1.65rem; }
`,
})
export class IndicadorKpiCard {
@@ -47,6 +47,8 @@ export class IndicadorKpiCard {
@Input() value?: string | number | null;
@Input() unit?: 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() notes: string[] = [];
@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'));
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
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.');
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', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
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(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');
// 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);
@@ -19,14 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[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') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`,
styles: `
:host { display: block; min-width: 0; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
:host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
`,
})
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 button { min-height: 44px; }
.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 .apply-button { margin-top: 0; }
@media (max-width: 550px) {
@@ -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(before[0].indicador.id).toBe('cacu_eu7');
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();
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));
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(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(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', () => {
// 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))
.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', () => {
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -210,13 +210,14 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
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 resultado maligno.');
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()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
expect(kpis()[4].querySelector('.value')).toBeNull();
});
it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => {
const pedidos = cargar(completo());
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
const primera = tarjetas()[0];
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
@@ -230,10 +231,13 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica');
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico');
});
it('sin CAM-03 en el catálogo conserva el KPI y la tarjeta con fuente local', () => {
const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
expect(kpis()).toHaveLength(5);
expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
expect(pedidos).not.toContain('cama_histopatologia_birads');
it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => {
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull();
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
});
it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => {
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
expect(kpis()).toHaveLength(5); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente');
});
});
@@ -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]);
});
});
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.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
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', () => {
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
]);
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]);
});
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', () => {
// 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);
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', () => {
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()]) });
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-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
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']);
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
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], '.value')).toBeUndefined();
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', () => {
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()[0], '.value')).toBe('5pacientes');
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', () => {
// 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
// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep.
// Covers the clinical section: its heading, and the controls the mockup does not have
// (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).
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
@@ -53,8 +53,8 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
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.
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
// The paired card has no card title; each donut names itself.
expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']);
// The paired card has no card title; each donut names itself. The other three indicators are in Histórico.
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');
@@ -73,21 +73,26 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
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 de histopatología tiene su lugar aunque la medida no figure en el catálogo', () => {
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
open('cama', CAMA);
const primera = root().querySelector('.catalog-grid')!.firstElementChild!;
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
expect(fixture.componentInstance.catalog().map(item => item.id)).not.toContain('cama_histopatologia_birads');
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
expect(tarjeta).not.toBeNull();
expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente');
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
// It comes first, as in the reference, and is not counted as a published indicator.
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
});
it('CaMa: si el catálogo publica la medida, Resumen dibuja una sola tarjeta de histopatología', () => {
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
expect(root().querySelectorAll('app-indicador-histopatologia-cama')).toHaveLength(1);
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS');
});
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica de CaMa', domain => {
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => {
open(domain, OTRO(domain));
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
});
it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => {
// Fails if any of the controls the mockup does not have comes back to CaMa's summary.
@@ -108,18 +113,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
expect(titles()).toEqual(before);
});
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => {
// Fails if CaMa's simplified section leaks into the other domains.
it.each(['tea', 'cacu'] as const)('%s usa el mismo resumen clínico que CaMa: sin buscador, fijados ni conteo de figuras', domain => {
open(domain, OTRO(domain));
expect(root().querySelector('.catalog-search')).not.toBeNull();
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
expect(section().textContent).toContain('2 figuras publicadas');
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
expect(root().querySelector('#dashboard-title')?.textContent?.trim()).toBe(domain === 'tea' ? 'Trastorno del espectro autista' : 'Cáncer cervicouterino');
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');
});
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();
expect(text()).not.toContain('Indicador de CaMa');
});
it('los controles propios de cada dominio se conservan al ir y volver', () => {
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
it('el resumen clínico es el mismo al ir y volver, y el catálogo no se mezcla', () => {
const abrir = (d: 'cacu' | 'cama', n: number) => {
fixture.componentInstance.changeDominio(d); 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;
abrir('cacu', 6);
expect(el().querySelector('.catalog-search')).not.toBeNull();
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
expect(el().querySelector('.catalog-search')).toBeNull();
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');
abrir('cama', 6);
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('cacu_');
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.searchVisible()).toBe(true);
expect(fixture.componentInstance.searchVisible()).toBe(false);
expect(el().textContent).toContain('Intervalo de análisis');
expect(el().textContent).not.toContain('cama_');
});
@@ -204,7 +204,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
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.
// The pair has no card title; each donut has its own heading.
expect(titulos).toEqual(['Resultado histopatológico por categoría BI-RADS']);
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');
});
@@ -213,7 +213,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
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());
expect(h3).toEqual([
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, 2025-S2',
'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(
@@ -19,7 +19,9 @@ export class IndicadoresDefinitions {
@Input() loading = false;
@Input() error = '';
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 figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION;
File diff suppressed because one or more lines are too long
@@ -173,14 +173,15 @@ describe('Seguimiento de TEA sobre FHIR', () => {
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,
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');
});
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
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
// Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
// the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
// 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'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
@@ -188,13 +189,27 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(detalle.grupo_edad).toBe('16-23 meses');
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
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')!;
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(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 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
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
@@ -1,5 +1,5 @@
// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows,
// rates and figures, and the catalog wiring of the local view. The fixtures are what WebApi publishes for the synthetic
// rates and figures, and the view that draws it. The fixtures are what WebApi publishes for the synthetic
// demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per
// period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator).
import { Component, input, output } from '@angular/core';
@@ -235,32 +235,124 @@ describe('Histopatología por BI-RADS: componente', () => {
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
});
afterEach(() => { f.destroy(); http.verify(); });
it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => {
f.componentRef.setInput('visible', false);
f.detectChanges();
expect(f.componentInstance.status()).toBe('deferred');
f.componentRef.setInput('visible', true);
f.detectChanges();
expect(f.componentInstance.status()).toBe('ready');
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma');
f.componentRef.setInput('tema', 'oscuro');
f.detectChanges();
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839');
const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos');
function flush(body: unknown = estratoFixture) {
const r = solicitud();
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
r.flush(body as Record<string, unknown>); f.detectChanges();
}
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.legend button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.status()).toBe('ready');
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
expect([...f.nativeElement.querySelectorAll('.tabs button')].map((b: Element) => b.textContent!.trim()))
.toEqual(['No maligno', 'Maligno']);
expect(f.nativeElement.querySelector('.tabs button[aria-selected=true]')!.textContent!.trim()).toBe('Maligno');
expect([...f.nativeElement.querySelectorAll('.tab-panel button')].map((b: Element) => b.textContent!.trim()))
.toEqual(['Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']);
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
const leyenda = f.nativeElement.querySelector('.legend') as HTMLElement;
const contexto = f.nativeElement.querySelector('.view-context') as HTMLElement;
expect(leyenda.compareDocumentPosition(grafica) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
expect(f.nativeElement.textContent).not.toContain('Filtro general aplicado');
expect(f.nativeElement.querySelector('.selection-status')).toBeNull();
expect(f.nativeElement.querySelector('.rate-states')).toBeNull();
expect(f.nativeElement.textContent).not.toContain('Sin pacientes con resultado de biopsia');
expect(contexto.textContent).toContain('Intervalo semestral');
expect(contexto.textContent).toContain('Periodo 2025-S1');
expect(f.componentInstance.selectionLabel).toBe('Maligno');
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(
['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']);
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent))).toEqual([
['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'],
['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'],
['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]);
expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional;');
});
it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => {
f.detectChanges(); flush();
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
expect(f.nativeElement.textContent).not.toContain('Volver');
boton('No maligno').click(); f.detectChanges();
const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
expect(b3.getAttribute('aria-pressed')).toBe('true');
expect(f.componentInstance.reading).toContain('Proporción con resultado lesión de riesgo (B3)');
b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' });
boton('Maligno').click(); f.detectChanges();
boton('Carcinoma invasor').click(); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' });
boton('Maligno').click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
http.expectNone(() => true);
});
it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => {
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 });
f.detectChanges();
expect(f.componentInstance.contextPeriod).toBe('2025-02');
it('una celda suprimida: la fila lo dice, la dona no suma un total parcial y el resto de las tasas se conserva', () => {
const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 });
f.detectChanges(); flush(d);
expect(f.componentInstance.status()).toBe('ready');
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 });
f.detectChanges();
expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos');
expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('Suprimido');
const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent));
expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4');
});
it('un estrato no publicado se lee «No disponible» en la tabla y en las tasas, y no como cero', () => {
const d = estrato(); d.filas = d.filas.filter(r => r['estrato'] !== 'BIRADS_6'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_6');
d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_6');
f.detectChanges(); flush(d);
const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement;
expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]);
expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('No disponible');
});
it('sin filas en el periodo lo dice y conserva la tabla vacía', () => {
const d = estrato(); d.filas = []; d.totales_estrato = [];
f.detectChanges(); flush(d);
expect(f.componentInstance.status()).toBe('empty');
expect(f.nativeElement.textContent).toContain('No hay resultados de biopsia para el periodo seleccionado.');
expect(f.nativeElement.textContent).toContain('No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.');
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
http.expectNone(() => true);
});
it('error se anuncia con reintento que recupera; una respuesta fuera de contrato es incompatible y no dibuja', () => {
f.detectChanges();
solicitud().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
f.componentInstance.retry(); flush({ ...estrato(), estrato: 'otro' });
expect(f.componentInstance.status()).toBe('incompatible');
expect(f.nativeElement.querySelector('[role=alert]').textContent).toContain('Respuesta incompatible');
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
});
it('un filtro general incompatible, otro dominio u otro indicador no piden datos', () => {
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('dominio', 'cacu'); f.detectChanges();
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
});
it('el tema oscuro redibuja con la paleta oscura sin pedir otra vez', () => {
f.detectChanges(); flush();
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
});
it('«Cómo leer» explica el denominador y añade lo que el servicio publique de las dos figuras, nada más', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const pedido = vi.fn(); f.componentInstance.metadataRequested.subscribe(pedido);
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
expect(pedido).toHaveBeenCalledTimes(1);
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('no entran en el denominador');
f.componentRef.setInput('metadata', { descripcion: 'No va', figuras_detalle: [
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] });
f.detectChanges();
const ayuda = f.nativeElement.querySelector('.methodology') as HTMLElement;
expect([...ayuda.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']);
for (const ausente of ['No va', 'Otra', 'No.']) expect(ayuda.textContent).not.toContain(ausente);
});
it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => {
@@ -15,7 +15,7 @@ export const ESTRATO_BIRADS = 'birads';
// The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never
// split among 4A/4B/4C nor added to them.
export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const;
export const ETIQUETA_ESTRATO: Readonly<Record<typeof ESTRATOS_BIRADS[number], string>> = {
const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6',
};
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
@@ -41,21 +41,19 @@ export interface Categoria { id: string; etiqueta: string; color: string; grupo:
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
export interface FilaBirads {
id: string; etiqueta: string;
// Categories with a biopsy result.
// The four categories with a result.
celdas: Record<string, Celda>;
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
aparte: Record<string, Celda>;
// Patients of the stratum, as the response publishes them.
total: Celda;
// Patients with a biopsy result: the denominator. Null while any result cell is unknown.
// Patients with a biopsy result: the denominator. Null while any of the four cells is unknown.
den: number | null; estado: Celda['estado'];
}
export interface ModeloHistopatologia {
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
// When set, the outer ring shows the subtype distribution within this group.
grupoAnilloExterior?: string;
}
export interface SeleccionHistopatologia { grupo: string; categoria?: string; }
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
@@ -68,7 +66,7 @@ const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').re
const miles = (v: number) => v.toLocaleString('es-MX');
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals.
const enFrase = (v: string) => v === v.toUpperCase() ? v : v.charAt(0).toLowerCase() + v.slice(1);
const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1);
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available.
@@ -185,9 +183,6 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
}
export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; }
export function categoriasExteriores(m: ModeloHistopatologia): Categoria[] {
return m.grupoAnilloExterior ? m.categorias.filter(c => c.grupo === m.grupoAnilloExterior) : m.categorias;
}
export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? [];
}
@@ -199,15 +194,12 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
if (traza === 'centro') return seleccionBase(m);
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
if (traza !== 'categorias') return sel;
const c = categoriasExteriores(m)[indice];
const c = m.categorias[indice];
if (!c) return sel;
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
}
/** The axis title says what the rate reads. */
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
if (m.grupoAnilloExterior) {
return 'Proporción con ' + enFrase(seleccionEtiqueta(m, sel)) + ' entre pacientes con resultado de biopsia';
}
if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia';
if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia';
return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel));
@@ -237,19 +229,16 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits.
export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
const p = c2Theme(tema);
const barras = !!m.grupoAnilloExterior;
const valores = tasas(m, sel);
const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
const tono = tonoDe(sel.categoria ?? sel.grupo);
const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color];
const y = valores.map(t => t.fila.etiqueta);
const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
const rango = rangoTasas(valores);
const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
return { data: [{
...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }),
uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false,
error_x: { type: 'data', symmetric: false, color: barras ? p.text : colores, thickness: 2, width: 6,
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
marker: { size: 12, color: colores }, cliponaxis: false,
error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6,
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
@@ -259,8 +248,8 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true,
...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
title: { text: estrecho ? 'Porcentaje' : (barras ? 'Porcentaje con ' : 'Porcentaje con resultado ') + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
font: { size: estrecho ? 11 : 12, color: p.text },
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
@@ -273,27 +262,17 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
const categorias = categoriasExteriores(m);
const exterior = categorias.map(c => m.totales[c.id]!);
const centro = m.grupoAnilloExterior
? `<b>${miles(k)}</b><br>de ${miles(total)}<br>con resultado`
: `<b>${miles(k)}</b><br>de ${miles(total)} con resultado`;
const exterior = m.categorias.map(c => m.totales[c.id]!);
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
const custom = (values: number[]) => {
const subtotal = values.reduce((s, n) => s + n, 0);
return values.map(n => [miles(n), subtotal === 0 ? '—' : shareText(n, subtotal)]);
};
const hoverExterior = m.grupoAnilloExterior
? { hovertemplate: '%{label}<br>%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)<extra></extra>' }
: hover;
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
const zoomGrupo = (id: string, hijos: readonly string[]) =>
sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1;
const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1;
const zoomDe = (values: number[]) => Math.max(1, ...values);
const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)');
const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias));
const categoriasZoom = categorias.map(c => zoomCategoria(c.id));
const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id));
const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({
...comun, ...hover, name, values, labels, hole, customdata: custom(values),
domain: caja(base, zoomDe(zoom)),
@@ -301,16 +280,16 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
});
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside',
text: [centro], textfont: { size: 16, color: p.text },
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con resultado`], 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>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1),
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } },
{ ...comun, ...hoverExterior, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
labels: categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: m.grupoAnilloExterior ? 1 : 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } },
anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)),
{ ...anillo('categorias', exterior, categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, categorias.map(c => c.color)), ...hoverExterior },
anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)),
], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
@@ -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.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' }));
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']);
@@ -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;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
// CaMa's day-count lines sit next to the histopathology bars, so they borrow that figure's blue, purple and rose.
const DIAS: Readonly<Record<string, { claro: string; oscuro: string; relleno: string }>> = {
cama_dias_toma_diagnostico: { claro: '#2F6DB3', oscuro: '#9DBFE3', relleno: '#9DBFE380' },
cama_eu38a: { claro: '#9C42C2', oscuro: '#D2A4EA', relleno: '#9C42C240' },
cama_dias_resultado_diagnostico: { claro: '#C24269', oscuro: '#E7A3B8', relleno: '#C2426940' },
};
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
const FONDO_AZUL = '#9DBFE380';
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.
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 };
}
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'>;
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data);
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line;
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 },
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: 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']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], 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 {
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 propio = DIAS[data.id];
const linea = propio ? (tema === 'oscuro' ? propio.oscuro : propio.claro) : c2Theme(tema).line;
const relleno = propio && tema === 'claro' ? propio.relleno : linea + '40';
const trazo = colorDeLinea(data.id, tema);
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea, 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 },
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: 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}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => {
@@ -63,15 +63,19 @@ describe('Figuras de histórico', () => {
expect(traza(data, 0).y).toEqual([30, 10]);
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', () => {
const color = (id: string, tema: 'claro' | 'oscuro') => {
it('las líneas de CaMa comparten el morado y, si hay banda, el fondo azul', () => {
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;
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' });
expect(color('cama_eu38a', 'claro')).toEqual({ linea: '#9C42C2', banda: '#9C42C240' });
expect(color('cama_dias_resultado_diagnostico', 'claro')).toEqual({ linea: '#C24269', banda: '#C2426940' });
expect(color('cama_dias_toma_diagnostico', 'oscuro').linea).toBe('#9DBFE3');
for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
expect(dias(id, 'claro')).toEqual({ linea: '#9C42C2', puntos: '#9C42C2', banda: '#9DBFE380' });
}
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', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
@@ -28,7 +28,7 @@ const PERSONALIZADO = -1;
// 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 }[] = [
{ 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: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
@@ -62,7 +62,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
<div class="controles">
<div class="controles compacto">
<h2>Filtros</h2>
<div class="controles-fila">
<div class="interval">
@@ -127,10 +127,22 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
</div>
`,
styles: `
@use '@angular/material' as mat;
: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);
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; }
// 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); }
.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; }
@@ -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); }
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
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 {
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { CACU_RESULTADO_KPI, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN } from './indicadores-kpi';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
import { pending } from './indicadores-memory';
import { Indicador } from './indicadores.models';
@@ -64,11 +64,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
}
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
function cards() {
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
}
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
// The shared request queue runs four at a time: flushing a batch starts the next.
function flushPanels(period: string, expected = definitions.length - 1) {
@@ -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', () => {
if (domain === 'cama') {
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']);
} else expect(anchor.id).toBe('cacu_eu7');
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,
};
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.
export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
@@ -25,7 +25,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
};
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
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 = {
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)' },
],
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,
],
};
@@ -15,7 +15,6 @@ import { IndicadoresPage } from './indicadores-page';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorPeriodFilters } from './indicador-period-filters';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
import { PlotlyFigure } from './indicadores.models';
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
@@ -37,9 +36,7 @@ describe('UX-04 navegación Angular', () => {
harness.detectChanges();
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
// CaMa leads with the histopathology card, which reads a local source; the figure request comes from the next one.
const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
.find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!;
const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
if (!card.visible) { card.setVisible(true); harness.detectChanges(); }
const req = http.expectOne(r => r.url.includes('/figuras/'));
req.flush({ data: [{ y: [0, null] }], layout: {} });
@@ -4,8 +4,7 @@
<h1 id="dashboard-title">Ficha del paciente</h1>
<p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
} @else {
@if (dominio !== 'cama') { <span class="domain">{{ domainTitles[dominio] }}, investigación</span> }
<h1 id="dashboard-title">{{ dominio === 'cama' ? 'Cáncer de mama' : 'Indicadores' }}</h1>
<h1 id="dashboard-title">{{ domainTitles[dominio] }}</h1>
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
}
</header>
@@ -23,10 +22,7 @@
@if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">Filtros</h2>
@if (dominio !== 'cama') {
<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"
<app-indicador-period-filters [state]="state" [compact]="true" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" />
</section>
@@ -50,7 +46,10 @@
@if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@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()" /> }
<!-- 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)">
@@ -76,7 +75,7 @@
<section class="graphic-section" aria-labelledby="graphic-section-title">
<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>
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
@@ -117,6 +116,7 @@
</div>
}
<div class="catalog-grid">
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
@for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
@@ -6,17 +6,16 @@
.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; }
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; }
// CaMa's filter block is one compact row, as in the reference.
.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); }
.global-filters .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-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);
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); }
.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); }
.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; }
@@ -37,16 +36,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 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)); } }
.kpi-section[data-domain='cama'] .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)); } }
.kpi-section[data-domain='cacu'] .kpi-grid {
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
align-items: stretch;
}
.kpi-section .kpi-grid { grid-auto-rows: 1fr; }
@container dashboard (min-width: 1350px) { .kpi-section .kpi-grid { grid-template-columns: repeat(min(5, var(--kpi-count)), minmax(0, 1fr)); } }
.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);
@@ -15,7 +15,6 @@ import { MatSelect } from '@angular/material/select';
import { NgModel } from '@angular/forms';
import { IndicadoresMemory } from './indicadores-memory';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
import { Indicador, PlotlyFigure } from './indicadores.models';
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
@@ -38,11 +37,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
function load(items: Indicador[] = [item, second], domain = 'tea') {
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
}
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
function cards() {
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
}
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); }
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
@@ -59,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', () => {
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);
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.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('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
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.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
expect(page.activeSection()).toBe('resumen');
@@ -112,7 +107,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(host.querySelector('mat-select')).toBeNull();
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
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);
});
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
@@ -127,7 +123,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
const header = host.querySelector('header'); toggle(); flushAll();
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
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', () => {
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
@@ -136,7 +132,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(header.querySelector('h2')?.textContent).toBe(title);
expect(header.querySelector('.card-identity 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);
});
it('UX-06B la navegación entre dominios es la del encabezado: la página no la duplica', () => {
@@ -329,7 +325,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
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 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');
for (let i = 0; i < 3; i++) {
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
@@ -31,6 +31,7 @@ import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
@@ -51,7 +52,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
@@ -101,6 +102,14 @@ export class IndicadoresPage {
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
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 renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver;
@@ -292,9 +301,12 @@ export class IndicadoresPage {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute, { optional: true });
dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
// At the start of the header line.
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
readonly domainLabels: Record<Dominio, string> = {
tea: 'trastorno del espectro autista', 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] };
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
@@ -314,15 +326,14 @@ export class IndicadoresPage {
private cardsDeCama(catalog: Indicador[]) {
const ids = catalog.map(item => item.id);
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) {
cards.unshift({
id: ID_HISTOPATOLOGIA_CAMA, titulo: 'Resultado histopatológico por categoría BI-RADS',
contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: ['fig_c2_barras', 'fig_c2_donas'],
});
}
// The histopathology card comes first, including when only the local source is available.
// The histopathology card keeps its place, first, whether pending or published.
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
}
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
get histopatologiaPendiente() {
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
}
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
@@ -347,9 +358,9 @@ export class IndicadoresPage {
readonly catalog = signal<Indicador[]>([]);
// Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null);
// CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws.
readonly searchVisible = computed(() => { const total = this.catalogOrder().length; return this.dominio !== 'cama' && total >= 2; });
// Stable presentation priority; pins still take precedence in the grid.
// The summary follows CaMa's mockup: no search box and no pins in any domain.
readonly searchVisible = computed(() => false);
// Stable presentation order. Pins no longer reorder the summary.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
return this.dominio === 'cacu'
@@ -365,9 +376,8 @@ export class IndicadoresPage {
return selected.length + ' indicadores';
});
readonly searchResults = computed(() => {
const selected = this.indicatorSelection();
const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id));
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
const selected = new Set(this.selectedIndicators());
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
});
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
@@ -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();
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
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);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(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();
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);
http.expectNone(() => true);
await fixture.whenStable();
@@ -8,7 +8,6 @@ import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadoresMemory } from './indicadores-memory';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
import { Indicador } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
@@ -36,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 card(id: string) { return cards().find(c => c.indicador.id === 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 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(); }
it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => {
const control = button('i3');
expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0);
expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false');
expect(control.getAttribute('aria-label')).toContain('Fijar indicador');
for (const key of ['Enter', ' ']) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
}
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');
it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
await pin('i3');
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(ids()).toEqual(items.map(i => i.id));
await pin('i3');
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
expect(ids()).toEqual(items.map(i => i.id));
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);
await pin('i4'); await pin('i2'); await pin('i0');
expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']);
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
expect(ids()).toEqual(items.map(i => i.id));
await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
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');
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']);
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();
expect(ids()).toEqual(['i0']);
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
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 () => {
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
@@ -83,12 +76,16 @@ describe('UX-06E.D.3.B fijación temporal', () => {
});
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));
// CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins.
// Its summary also leads with the histopathology card, which is not part of the catalog and cannot be pinned.
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]);
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
const memory = TestBed.inject(IndicadoresMemory);
expect(memory.isPinned('cacu', 'i1')).toBe(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 () => {
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
@@ -96,10 +93,12 @@ describe('UX-06E.D.3.B fijación temporal', () => {
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
});
it('mover la tarjeta conserva foco en su botón existente', async () => {
const control = button('i4'); control.focus(); await pin('i4');
expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control);
await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true);
it('fijar no mueve la tarjeta ni pide figuras', async () => {
const before = cards();
await pin('i4');
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 () => {
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 { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card';
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 ids() { return cards().map(c => c.indicador.id); }
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(); }
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 })));
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(cards()).toHaveLength(count);
http.expectNone(() => true);
});
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
load();
expect(select()!.multiple).toBe(true);
expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(result()).toBe('Mostrando 5 de 5 indicadores.');
expect(showAll().disabled).toBe(true);
expect(fixture.nativeElement.textContent).not.toContain('Mostrando 5 de 5 indicadores.');
http.expectNone(() => true);
});
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(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
expect(page.catalog()).toBe(original);
@@ -76,9 +70,8 @@ describe('Selección de indicadores gráficos', () => {
load(); choose([]);
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
expect(showAll().disabled).toBe(false);
showAll().click(); fixture.detectChanges();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
page.showAllIndicators(); fixture.detectChanges();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull();
http.expectNone(() => true);
});
it('marcar todos equivale a no filtrar', () => {
@@ -90,26 +83,18 @@ describe('Selección de indicadores gráficos', () => {
choose(['A01']);
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();
Element.prototype.scrollIntoView = scroll;
load(); choose(['A01']);
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go'))
.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(document.querySelector('.indicator-select-panel')).toBeNull();
page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable();
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
expect(select()!.panelOpen).toBe(false);
await settle(1);
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); });
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
// Already visible: the selection is untouched.
page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable();
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: {} }));
});
it('no muestra el botón flotante de navegación por indicadores', () => {
@@ -61,15 +61,23 @@
@if (teaData; as response) {
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</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>
@if (response.resumen_eeg.validadas) {
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</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>
} @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>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
@@ -12,7 +12,7 @@ import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
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';
@Component({
@@ -98,6 +98,8 @@ export class IndicadoresTracking implements OnChanges {
if (result.data) {
const data = result.data;
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.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();
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);
// The pinned indicator leads; the other selected one keeps its component.
expect(cards()).toEqual([before[4], before[3]]);
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
// Pins no longer reorder; the selected indicators keep catalog order and their components.
expect(cards()).toEqual([before[3], before[4]]);
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();
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 => {
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', () => {
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', () => {
const http = TestBed.inject(HttpTestingController); let result: unknown;
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;
@@ -38,7 +38,13 @@
<mat-card-content>
<ul>
@for (item of placeholders; track item.key) {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
@if (item.key === 'recurrence' && p.idField === 'pac_id') {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><app-cama-recurrencia [pacId]="+p.patientId" /></li>
} @else if (item.key === 'survival' && p.idField === 'pac_id') {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><app-cama-supervivencia [pacId]="+p.patientId" /></li>
} @else {
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
}
}
</ul>
<p class="availability">{{ recommendationsUnavailable }}</p>
@@ -3,17 +3,19 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { CamaRecurrencia } from './cama-recurrencia';
import { CamaSupervivencia } from './cama-supervivencia';
import {
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
} from './cama-patient.models';
/**
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
* survival and prognostic factors are placeholders until a validated model supplies them.
* Individual record of a CaMa follow-up patient: what the follow-up list carries and, in its prognosis card, the recurrence and
* survival figures of the clinical scenarios the patient belongs to.
*/
@Component({
selector: 'app-cama-patient-card',
imports: [MatButtonModule, MatCardModule, MatIconModule],
imports: [CamaRecurrencia, CamaSupervivencia, MatButtonModule, MatCardModule, MatIconModule],
templateUrl: './cama-patient-card.html',
styleUrl: './cama-patient-card.scss',
})
@@ -0,0 +1,55 @@
import { PlotlyFigure } from '../../indicadores.models';
import { RecurrenciaFigura } from './cama-recurrencia.models';
const decimales = new Intl.NumberFormat('es-MX');
const finitos = (valores: (number | null)[]) => valores.filter((v): v is number => v !== null && Number.isFinite(v));
/**
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull (dotted past the
* follow-up), and the combined estimate at each horizon with its bootstrap interval.
*/
export function figuraRecurrencia(figura: RecurrenciaFigura): PlotlyFigure {
const km = figura.km;
const seguimiento = km.months[km.months.length - 1];
const combinado = figura.points.COMB;
const tiempos = figura.weibull.t;
const dentro = tiempos.map(t => t <= seguimiento);
const trazo = (S: (number | null)[], dentroDelSeguimiento: boolean) =>
S.map((v, i) => (dentro[i] === dentroDelSeguimiento || (!dentroDelSeguimiento && tiempos[i] === seguimiento) ? v : null));
const todos = [...finitos(km.low), ...finitos(km.high), ...finitos(combinado.low), ...finitos(combinado.high),
...finitos(figura.weibull.S), ...finitos(figura.weibull_fractional.S)];
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
const horizontes = figura.horizons_months;
const S = combinado.S.map(v => v ?? NaN);
return {
data: [
{ x: km.months, y: km.low, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
{ x: km.months, y: km.high, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty',
fillcolor: 'rgba(154,165,177,0.3)', hoverinfo: 'skip', showlegend: false },
{ x: km.months, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
{ x: tiempos, y: trazo(figura.weibull.S, true), type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
{ x: tiempos, y: trazo(figura.weibull.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#1f77b4', dash: 'dot' },
hoverinfo: 'skip', showlegend: false },
{ x: tiempos, y: trazo(figura.weibull_fractional.S, true), type: 'scatter', mode: 'lines',
line: { width: 3, color: '#d1495b', dash: 'dash' }, name: 'Weibull fraccional' },
{ x: tiempos, y: trazo(figura.weibull_fractional.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#d1495b', dash: 'dot' },
hoverinfo: 'skip', showlegend: false },
{ x: horizontes, y: S, type: 'scatter', mode: 'markers',
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
error_y: { type: 'data', symmetric: false, array: combinado.high.map((v, i) => (v ?? NaN) - S[i]),
arrayminus: combinado.low.map((v, i) => S[i] - (v ?? NaN)), color: '#6a3d9a', thickness: 2, width: 5 },
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
],
layout: {
title: { text: `${figura.escenario}<br>${figura.cohorte_nombre} · n=${decimales.format(figura.n)}, recaídas=${decimales.format(figura.recaidas)}`,
font: { size: 15 } },
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, figura.months_max + 0.8], dtick: 12, zeroline: false },
yaxis: { title: { text: 'Libre de recaída S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
margin: { l: 70, r: 20, t: 70, b: 60 },
hovermode: 'x unified',
},
config: { responsive: true, displaylogo: false },
};
}
@@ -0,0 +1,38 @@
@switch (estado()) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de recurrencia" /> }
@case ('sin-modelo') { <p class="availability">No hay una cohorte armada para el análisis de recurrencia.</p> }
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de recurrencia.</p> }
@default {
@if (!postratamiento()) {
<p class="availability">El análisis de recurrencia es para pacientes que ya terminaron su tratamiento.</p>
} @else {
@if (deLaPaciente().length) {
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico de la paciente" [value]="elegido()?.cohorte + '|' + elegido()?.escenario"
(change)="elegirDePaciente($event.value)">
@for (e of deLaPaciente(); track e.cohorte + e.escenario) {
<mat-button-toggle [value]="e.cohorte + '|' + e.escenario">{{ nombreCohorte(e.cohorte) }} · {{ e.escenario }}</mat-button-toggle>
}
</mat-button-toggle-group>
} @else {
<p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo. Elige uno del menú.</p>
}
<div class="menu">
<mat-form-field appearance="outline">
<mat-label>Cohorte</mat-label>
<mat-select [value]="cohorteDelMenu()" (selectionChange)="elegirCohorte($event.value)">
@for (c of cohortes(); track c.id) { <mat-option [value]="c.id">{{ c.nombre }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Escenario</mat-label>
<mat-select [value]="elegido()?.escenario" (selectionChange)="elegir(cohorteDelMenu(), $event.value)">
@for (e of escenariosDelMenu(); track e.nombre) { <mat-option [value]="e.nombre">{{ e.nombre }}</mat-option> }
</mat-select>
</mat-form-field>
</div>
}
@if (calculando()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de recurrencia del escenario clínico" /> }
@if (mensaje(); as texto) { <p class="availability" role="status">{{ texto }}</p> }
}
}
@@ -0,0 +1,49 @@
/** The recurrence analysis as `/cama/recurrencia` gives it: the scenarios of each cohort, a scenario's figure and a patient's scenarios. */
export interface RecurrenciaEscenario { nombre: string; condiciones: Record<string, string[]>; n: number; recaidas: number; dibujable: boolean }
export interface RecurrenciaCohorte { id: string; nombre: string; estado: 'calculando' | 'listo' | 'error'; error: string | null; escenarios: RecurrenciaEscenario[] }
export interface RecurrenciaEscenarios { build: number; horizontes: number[]; cohortes: RecurrenciaCohorte[] }
export interface RecurrenciaDePaciente { build: number; pac_id: number; postratamiento: boolean; escenarios: { cohorte: string; escenario: string }[] }
export interface RecurrenciaFigura {
cohorte: string;
cohorte_nombre: string;
escenario: string;
n: number;
recaidas: number;
horizons_months: number[];
months_max: number;
bootstrap_replicas: number;
km: { months: number[]; S: number[]; low: number[]; high: number[] };
weibull: { t: number[]; S: (number | null)[] };
weibull_fractional: { t: number[]; S: (number | null)[] };
points: { COMB: { S: (number | null)[]; low: (number | null)[]; high: (number | null)[] } };
}
export type RecurrenciaRespuestaFigura = { estado: 'calculando' } | { estado: 'listo'; figura: RecurrenciaFigura };
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
export function recurrenciaEscenarios(v: unknown): RecurrenciaEscenarios {
if (!record(v) || typeof v['build'] !== 'number' || !numbers(v['horizontes']) || !Array.isArray(v['cohortes'])
|| !v['cohortes'].every(c => record(c) && typeof c['id'] === 'string' && typeof c['nombre'] === 'string' && Array.isArray(c['escenarios']))) {
throw new Error('Respuesta de escenarios de recurrencia inválida');
}
return v as unknown as RecurrenciaEscenarios;
}
export function recurrenciaDePaciente(v: unknown): RecurrenciaDePaciente {
if (!record(v) || typeof v['postratamiento'] !== 'boolean' || !Array.isArray(v['escenarios'])
|| !v['escenarios'].every(e => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')) {
throw new Error('Respuesta de recurrencia de la paciente inválida');
}
return v as unknown as RecurrenciaDePaciente;
}
export function recurrenciaFigura(v: unknown): RecurrenciaFigura {
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte'] !== 'string' || typeof v['n'] !== 'number'
|| typeof v['recaidas'] !== 'number' || !numbers(v['horizons_months']) || !record(v['km']) || !numbers(v['km']['months'])
|| !numbers(v['km']['S']) || !record(v['weibull']) || !record(v['weibull_fractional']) || !record(v['points'])) {
throw new Error('Respuesta de figura de recurrencia inválida');
}
return v as unknown as RecurrenciaFigura;
}
@@ -0,0 +1,4 @@
:host { display: block; min-width: 0; --plot-height: 420px; }
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
.menu { display: flex; flex-wrap: wrap; gap: 0.75rem; margin: 0.75rem 0; }
.availability { margin: 0; }
@@ -0,0 +1,29 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';
import { map } from 'rxjs';
import {
recurrenciaDePaciente, recurrenciaEscenarios, recurrenciaFigura, RecurrenciaRespuestaFigura,
} from './cama-recurrencia.models';
@Injectable({ providedIn: 'root' })
export class CamaRecurrenciaService {
private readonly http = inject(HttpClient);
/** The scenarios of each cohort, with their size and whether they have enough recurrences to be drawn. */
escenarios() {
return this.http.get<unknown>('/cama/recurrencia/escenarios').pipe(map(recurrenciaEscenarios));
}
/** The scenarios a patient's covariates meet, in each cohort; empty for a patient who is not after treatment. */
deLaPaciente(pacId: number) {
return this.http.get<unknown>(`/cama/recurrencia/pacientes/${pacId}`).pipe(map(recurrenciaDePaciente));
}
/** The figure of one scenario; `calculando` while the cohort's models are being computed. */
figura(cohorte: string, escenario: string) {
const params = new HttpParams().set('cohorte', cohorte).set('escenario', escenario);
return this.http.get<unknown>('/cama/recurrencia/figura', { params, observe: 'response' }).pipe(
map((r: HttpResponse<unknown>): RecurrenciaRespuestaFigura =>
r.status === 202 ? { estado: 'calculando' } : { estado: 'listo', figura: recurrenciaFigura(r.body) }));
}
}
@@ -0,0 +1,95 @@
import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { forkJoin, Subscription, timer } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { PlotlyFigure } from '../../indicadores.models';
import { figuraRecurrencia } from './cama-recurrencia-figura';
import { RecurrenciaCohorte } from './cama-recurrencia.models';
import { CamaRecurrenciaService } from './cama-recurrencia.service';
const ESPERA_CALCULO_MS = 5000;
/**
* A patient's recurrence: the clinical scenarios her covariates meet and, from a menu, any scenario of either cohort, with the
* figure of the one chosen, computed over the live cohort.
*/
@Component({
selector: 'app-cama-recurrencia',
imports: [MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
templateUrl: './cama-recurrencia.html',
styleUrl: './cama-recurrencia.scss',
})
export class CamaRecurrencia {
readonly pacId = input.required<number>();
readonly estado = signal<'cargando' | 'listo' | 'sin-modelo' | 'error'>('cargando');
readonly postratamiento = signal(false);
readonly cohortes = signal<RecurrenciaCohorte[]>([]);
readonly deLaPaciente = signal<{ cohorte: string; escenario: string }[]>([]);
readonly elegido = signal<{ cohorte: string; escenario: string } | null>(null);
readonly figura = signal<PlotlyFigure | null>(null);
readonly calculando = signal(false);
readonly mensaje = signal<string | null>(null);
private readonly menuCohorte = signal<string | null>(null);
readonly cohorteDelMenu = computed(() => this.menuCohorte() ?? this.elegido()?.cohorte ?? this.cohortes()[0]?.id ?? '');
readonly escenariosDelMenu = computed(() =>
this.cohortes().find(c => c.id === this.cohorteDelMenu())?.escenarios.filter(e => e.dibujable) ?? []);
private readonly servicio = inject(CamaRecurrenciaService);
private readonly destroy = inject(DestroyRef);
private pedido?: Subscription;
constructor() {
effect(() => this.cargar(this.pacId()));
}
nombreCohorte(id: string) { return this.cohortes().find(c => c.id === id)?.nombre ?? id; }
private cargar(pacId: number) {
this.estado.set('cargando'); this.limpiar(); this.elegido.set(null); this.menuCohorte.set(null);
forkJoin({ menu: this.servicio.escenarios(), paciente: this.servicio.deLaPaciente(pacId) })
.pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: ({ menu, paciente }) => {
this.cohortes.set(menu.cohortes);
this.postratamiento.set(paciente.postratamiento);
this.deLaPaciente.set(paciente.escenarios);
this.estado.set('listo');
if (paciente.postratamiento && paciente.escenarios.length) this.elegir(paciente.escenarios[0].cohorte, paciente.escenarios[0].escenario);
},
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
});
}
private limpiar() { this.figura.set(null); this.mensaje.set(null); this.calculando.set(false); this.pedido?.unsubscribe(); }
elegirDePaciente(clave: string) { const [cohorte, ...resto] = clave.split('|'); this.elegir(cohorte, resto.join('|')); }
elegirCohorte(cohorte: string) { this.menuCohorte.set(cohorte); this.elegido.set(null); this.limpiar(); }
elegir(cohorte: string, escenario: string) {
this.limpiar();
this.elegido.set({ cohorte, escenario }); this.menuCohorte.set(cohorte); this.calculando.set(true);
const vigente = () => this.elegido()?.cohorte === cohorte && this.elegido()?.escenario === escenario;
const pedir = () => {
this.pedido = this.servicio.figura(cohorte, escenario).subscribe({
next: r => {
if (!vigente()) return;
if (r.estado === 'calculando') {
this.mensaje.set('Calculando los modelos de la cohorte; la figura aparecerá en cuanto estén listos.');
this.pedido = timer(ESPERA_CALCULO_MS).subscribe(() => { if (vigente()) pedir(); });
return;
}
this.calculando.set(false); this.mensaje.set(null); this.figura.set(figuraRecurrencia(r.figura));
},
error: (e: { status?: number }) => {
if (!vigente()) return;
this.calculando.set(false);
this.mensaje.set(e?.status === 404 ? 'El escenario tiene pocas recaídas para dibujar su curva.' : 'No se pudo calcular la figura. Intenta nuevamente.');
},
});
};
pedir();
}
}
@@ -0,0 +1,45 @@
import { PlotlyFigure } from '../../indicadores.models';
import { SupervivenciaFigura } from './cama-supervivencia.models';
const decimales = new Intl.NumberFormat('es-MX');
/**
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the
* LR + HBN combined survival at each horizon with its bootstrap interval.
*/
export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure {
const meses = figura.months ?? [];
const km = figura.km!;
const curvas = figura.curve_months ?? [];
const combinados = figura.points.filter(p => p.model === 'COMB');
const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1];
const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])]
.filter(v => Number.isFinite(v));
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
return {
data: [
{ x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
{ x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)',
hoverinfo: 'skip', showlegend: false },
{ x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
{ x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
{ x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' },
name: 'Weibull fraccional' },
{ x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers',
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low),
color: '#6a3d9a', thickness: 2, width: 5 },
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
],
layout: {
title: { text: `${figura.scenario}<br>n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } },
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false },
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
margin: { l: 70, r: 20, t: 70, b: 60 },
hovermode: 'x unified',
},
config: { responsive: true, displaylogo: false },
};
}
@@ -0,0 +1,16 @@
@switch (estado()) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de supervivencia" /> }
@case ('sin-modelo') { <p class="availability">No hay un modelo de supervivencia en producción.</p> }
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de supervivencia.</p> }
@case ('sin-escenarios') { <p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo.</p> }
@default {
@if (escenarios().length > 1) {
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico" [value]="elegido()" (change)="elegir($event.value)">
@for (nombre of escenarios(); track nombre) { <mat-button-toggle [value]="nombre">{{ nombre }}</mat-button-toggle> }
</mat-button-toggle-group>
}
@if (cargandoFigura()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de supervivencia del escenario clínico" /> }
@if (sinDibujo(); as mensaje) { <p class="availability" role="status">{{ mensaje }}</p> }
}
}
@@ -0,0 +1,42 @@
/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */
export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number }
export interface SupervivenciaFigura {
scenario: string;
members: number;
deaths: number;
drawable: boolean;
horizons: number[];
months?: number[];
km?: { S: number[]; lo: number[]; hi: number[] };
curve_months?: number[];
weibull?: { k: number; S: number[] };
fractional?: { k: number; alpha: number; beta: number; S: number[] };
points: SupervivenciaPunto[];
}
export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] }
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios {
if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string')
|| typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') {
throw new Error('Respuesta de escenarios de supervivencia inválida');
}
return v as unknown as SupervivenciaEscenarios;
}
export function supervivenciaFigura(v: unknown): SupervivenciaFigura {
if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number'
|| typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) {
throw new Error('Respuesta de figura de supervivencia inválida');
}
if (v['drawable']) {
const km = v['km'], w = v['weibull'], f = v['fractional'];
if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi'])
|| !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta');
}
return v as unknown as SupervivenciaFigura;
}
@@ -0,0 +1,3 @@
:host { display: block; min-width: 0; --plot-height: 420px; }
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
.availability { margin: 0; }
@@ -0,0 +1,20 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models';
@Injectable({ providedIn: 'root' })
export class CamaSupervivenciaService {
private readonly http = inject(HttpClient);
/** The scenarios a patient belongs to, from her variables over the timeline. */
escenarios(pacId: number) {
return this.http.get<unknown>(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios));
}
/** The figure of one scenario over the production model and the live cohort. */
figura(escenario: string) {
const params = new HttpParams().set('escenario', escenario);
return this.http.get<unknown>('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura));
}
}
@@ -0,0 +1,63 @@
import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { Subscription } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { PlotlyFigure } from '../../indicadores.models';
import { figuraSupervivencia } from './cama-supervivencia-figura';
import { CamaSupervivenciaService } from './cama-supervivencia.service';
/**
* A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in
* production and the live cohort.
*/
@Component({
selector: 'app-cama-supervivencia',
imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
templateUrl: './cama-supervivencia.html',
styleUrl: './cama-supervivencia.scss',
})
export class CamaSupervivencia {
readonly pacId = input.required<number>();
readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando');
readonly escenarios = signal<string[]>([]);
readonly elegido = signal<string | null>(null);
readonly figura = signal<PlotlyFigure | null>(null);
readonly cargandoFigura = signal(false);
readonly sinDibujo = signal<string | null>(null);
private readonly servicio = inject(CamaSupervivenciaService);
private readonly destroy = inject(DestroyRef);
private pedido?: Subscription;
constructor() {
effect(() => this.cargar(this.pacId()));
}
private cargar(pacId: number) {
this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null);
this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: respuesta => {
this.escenarios.set(respuesta.scenarios);
if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; }
this.estado.set('listo');
this.elegir(respuesta.scenarios[0]);
},
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
});
}
elegir(escenario: string) {
this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true);
this.pedido?.unsubscribe();
this.pedido = this.servicio.figura(escenario).subscribe({
next: f => {
this.cargandoFigura.set(false);
if (this.elegido() !== escenario) return;
if (f.drawable) this.figura.set(figuraSupervivencia(f));
else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`);
},
error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); },
});
}
}
@@ -8,33 +8,13 @@
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
@if (lectura.datos.cohorte; as cohorte) {
<h5>Cohorte</h5>
<dl class="metadata">
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
</dl>
<details>
<summary>Variables del modelo PIMM</summary>
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
<dl class="metadata">
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
</dl>
</details>
} @else {
<p role="status">Sin membresía en la cohorte vigente.</p>
}
@if (lectura.datos.riesgo; as riesgo) {
@let riesgo = lectura.datos.riesgo;
<h5>Modelo y evaluación</h5>
<dl class="metadata">
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
</dl>
@@ -46,7 +26,6 @@
<th scope="col">Horizonte (años)</th>
<th scope="col">Probabilidad (%)</th>
<th scope="col">Intervalo de confianza (%)</th>
<th scope="col">Estado de evaluación</th>
</tr></thead>
<tbody>
@for (h of riesgo.horizontes; track h.horizonte_anios) {
@@ -54,14 +33,12 @@
<th scope="row">{{ h.horizonte_anios }}</th>
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
</tr>
}
</tbody>
</table>
</div>
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
}
}
<p class="recommendations">Recomendaciones no disponibles.</p>
@@ -1,46 +1,39 @@
import { Observable } from 'rxjs';
export type EstadoEvaluacionCacu = 'preliminary' | 'final';
export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo';
export interface CohorteRiesgoCacu {
url: string;
version: string;
fecha_indice: string;
tipo_censura: TipoCensuraCacu | null;
c: number | null;
l: number | null;
r: number | null;
pap_0: string | null;
hpv_0: string | null;
}
export interface HorizonteRiesgoCacu {
/** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */
horizonte_anios: number;
/** Transport values remain probabilities in [0, 1], never percentages. */
probabilidad: number;
ic_bajo?: number | null;
ic_alto?: number | null;
estado: EstadoEvaluacionCacu;
}
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
export interface LoteRiesgoCacu {
lote_id: number;
/** The resource's id, `<lote_id>-<pac_id>`. */
id: string;
modelo_nombre: string;
modelo_version: string;
/** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */
fecha_indice: string;
evaluado_en: string;
estado_lote: EstadoEvaluacionCacu;
/** The prediction's outcome code (e.g. `cin2_mas`) and its display. */
desenlace: string;
desenlace_texto: string | null;
horizontes: HorizonteRiesgoCacu[];
}
/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
export interface RiesgoPacienteCacu {
simulado: true;
cohorte: CohorteRiesgoCacu | null;
riesgo: LoteRiesgoCacu | null;
riesgo: LoteRiesgoCacu;
}
/** `null` when the patient has no risk data. */
/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */
export interface PacienteRiesgoProvider {
obtener(pacId: string): Observable<unknown>;
}
@@ -1,14 +1,17 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { inject, InjectionToken } from '@angular/core';
import { catchError, of, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data.
// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/<pac_id>`, the identifier a follow-up row
// carries as `pac_id`; an empty Bundle (or a 404) is a patient without risk data.
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
obtener: (pacId: string) => http.get<unknown>('/cacu/fhir/RiskAssessment', {
params: new HttpParams().set('subject', `Patient/${pacId}`),
}).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
@@ -4,7 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import { of, Subject, throwError } from 'rxjs';
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
@@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
TestBed.inject(HttpTestingController).verify();
});
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => {
const f = setup(), root: HTMLElement = f.nativeElement;
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42')
.flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' });
f.detectChanges();
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('Recomendaciones no disponibles');
@@ -33,27 +33,33 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
});
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
it('un Bundle vacío es una paciente sin riesgo confirmado', () => {
const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) });
expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(f.nativeElement.querySelector('table')).toBeNull();
});
it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => {
const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data));
data.riesgo!.horizontes[1].estado = 'preliminary';
const baseline = structuredClone(data);
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
expect(root.querySelectorAll('thead th')).toHaveLength(4);
expect(root.querySelectorAll('thead th')).toHaveLength(3);
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
expect(root.textContent).toContain('Final (final)');
expect(root.textContent).toContain('Preliminar (preliminary)');
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) {
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
expect(root.textContent).toContain(value);
}
// The record no longer shows the cohort's internals (its definition, version or model variables).
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/);
expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado');
expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV');
expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/);
// Internal batch key stays in the contract, never in a UI label.
expect(root.textContent).not.toContain('lote_id');
// The resource id (batch and patient) stays in the contract, never in a UI label.
expect(root.textContent).not.toMatch(/lote_id|12-42/);
expect(data).toEqual(baseline);
});
@@ -67,17 +73,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(getComputedStyle(scroll).maxWidth).toBe('100%');
expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem');
expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky');
expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM');
expect(root.textContent).toContain('no constituyen un diagnóstico');
});
it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => {
const data = riesgoCacuEjemplo();
data.riesgo!.estado_lote = 'preliminary';
data.riesgo!.horizontes = [
{ horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' },
{ horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' },
{ horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' },
data.entry[0].resource.status = 'preliminary';
data.entry[0].resource.prediction = [
prediccion(0, '2026-06-01', '2026-12-01', [0, 0]),
prediccion(1, '2026-06-01', '2034-06-01'),
prediccion(0.00123, '2026-06-01', '2038-09-01'),
];
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
@@ -86,31 +90,9 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
expect(root.textContent).toContain('Preliminar (preliminary)');
});
it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => {
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
const data = riesgoCacuEjemplo();
data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null };
const f = setup({ obtener: () => of(data) });
const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent);
expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']);
expect(f.nativeElement.textContent).not.toMatch(/undefined|null/);
});
it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => {
const data = riesgoCacuEjemplo();
if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null;
if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null;
if (caso === 'horizontes') data.riesgo!.horizontes = [];
const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement;
if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente');
if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente');
if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados');
if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull();
expect(root.textContent).toContain('Información simulada');
expect(root.textContent).toContain('Recomendaciones no disponibles');
});
it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => {
const data = { ...riesgoCacuEjemplo(), simulado };
if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag;
const f = setup({ obtener: () => of(data) });
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
expect(f.nativeElement.textContent).not.toContain('modelo-cacu');
@@ -118,7 +100,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
});
it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => {
const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12;
const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12;
const f = setup({ obtener: () => of(data) });
expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull();
expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0);
@@ -134,14 +116,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
it('aísla estado y fixture entre instancias sin reutilizar información', () => {
const source = new Subject<unknown>(), f = setup({ obtener: () => source });
const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges();
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges();
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
f.destroy();
const otra = TestBed.createComponent(PacienteRiesgoTabla);
otra.componentRef.setInput('pacId', '43'); otra.detectChanges();
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
expect(otra.nativeElement.querySelector('table')).toBeNull();
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08);
otra.destroy(); expect(source.observed).toBe(false);
});
@@ -14,8 +14,10 @@ export class PacienteRiesgoState {
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe(
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
map((respuesta): PacienteRiesgoEstado => {
const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id);
return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos };
}),
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
@@ -1,20 +1,51 @@
import { RiesgoPacienteCacu } from './paciente-riesgo.models';
/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */
export function riesgoCacuEjemplo(): RiesgoPacienteCacu {
const CS = 'https://isssteleon.org/fhir/CodeSystem';
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
return {
outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] },
probabilityDecimal: p, whenPeriod: { start: inicio, end: fin },
...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}),
};
}
/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as
* `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */
export function riesgoCacuEjemplo(): any {
return {
resourceType: 'Bundle', type: 'searchset', total: 1,
entry: [{
fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42',
resource: {
resourceType: 'RiskAssessment', id: '12-42', status: 'final',
meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] },
subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z',
method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] },
prediction: [
prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]),
prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]),
prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]),
],
},
search: { mode: 'match' },
}],
};
}
/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */
export function riesgoCacuVista(): RiesgoPacienteCacu {
return {
simulado: true,
cohorte: {
url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15',
tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO',
},
riesgo: {
lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0',
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final',
id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01',
evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia',
horizontes: [
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' },
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' },
{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
],
},
};
@@ -1,121 +1,89 @@
import { riesgoCacuEjemplo } from './paciente-riesgo.testing';
import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation';
import { TipoCensuraCacu } from './paciente-riesgo.models';
describe('RIESGO-CACU-02: frontera del contrato DEV', () => {
it('conserva todos los campos del ejemplo externo y copia los objetos', () => {
const recurso = (v: any) => v.entry[0].resource;
describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => {
it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => {
const entrada = riesgoCacuEjemplo();
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
salida.riesgo!.horizontes[0].probabilidad = 0;
salida.cohorte!.c = -999;
const salida = riesgoPacienteResponse(entrada, '42')!;
expect(salida).toEqual(riesgoCacuVista());
salida.riesgo.horizontes[0].probabilidad = 0;
expect(entrada).toEqual(riesgoCacuEjemplo());
});
it('admite campos aditivos sin eliminarlos ni renombrarlos', () => {
const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } };
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => {
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull();
expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull();
});
it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])(
'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null;
expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo);
},
);
it('preserva los nulos independientes y el sentinel basal del contrato', () => {
it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null };
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
entrada.riesgo = null;
entrada.cohorte.c = null;
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
entrada.cohorte = null;
expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null });
recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')];
expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]);
});
it('no impone dependencia entre cohorte nullable y riesgo nullable', () => {
it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => {
const entrada = riesgoCacuEjemplo();
entrada.cohorte = null;
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
recurso(entrada).prediction.reverse();
recurso(entrada).note = [{ text: 'simulado' }];
expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista());
});
it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => {
it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({
horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final',
}));
expect(riesgoPacienteResponse(entrada)).toEqual(entrada);
});
it.each([
{}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null },
{ ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 },
])('conserva IC incompletos sin generar límites: %j', limites => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }];
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false);
const p = recurso(entrada).prediction[0];
if (ext === undefined) delete p.extension; else p.extension = ext;
const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0];
expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]);
expect(tieneIntervalo(h)).toBe(false);
});
it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => {
const entrada = riesgoCacuEjemplo();
entrada.riesgo!.estado_lote = 'preliminary';
entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }];
const salida = riesgoPacienteResponse(entrada);
expect(salida).toEqual(entrada);
expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true);
recurso(entrada).status = 'preliminary';
recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])];
const salida = riesgoPacienteResponse(entrada)!;
expect(salida.riesgo.estado_lote).toBe('preliminary');
expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p });
expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true);
});
const invalidos: [string, (v: any) => void][] = [
['no simulado', v => v.simulado = false],
['simulado string', v => v.simulado = 'true'],
['sin simulado', v => delete v.simulado],
['sin cohorte', v => delete v.cohorte],
['sin riesgo', v => delete v.riesgo],
['cohorte lista', v => v.cohorte = []],
['URL ajena', v => v.cohorte.url = 'otra'],
['versión ausente', v => delete v.cohorte.version],
['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'],
['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'],
['basal string', v => v.cohorte.c = '0'],
['variable no finita', v => v.cohorte.l = Infinity],
['variable omitida', v => delete v.cohorte.r],
['pap no textual', v => v.cohorte.pap_0 = 5],
['hpv no textual', v => v.cohorte.hpv_0 = false],
['lote fraccionario', v => v.riesgo.lote_id = 1.5],
['lote string', v => v.riesgo.lote_id = '12'],
['modelo omitido', v => delete v.riesgo.modelo_nombre],
['versión no textual', v => v.riesgo.modelo_version = 2],
['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'],
['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'],
['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'],
['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'],
['sin horizontes', v => delete v.riesgo.horizontes],
['horizontes nulos', v => v.riesgo.horizontes = null],
['horizonte nulo', v => v.riesgo.horizontes[0] = null],
['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'],
['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN],
['horizontes desordenados', v => v.riesgo.horizontes.reverse()],
['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1],
['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01],
['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01],
['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'],
['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null],
['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN],
['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'],
['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01],
['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01],
['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'],
['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })],
['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07],
['no es Bundle', v => v.resourceType = 'RiskAssessment'],
['Bundle no searchset', v => v.type = 'collection'],
['sin total', v => delete v.total],
['entry no lista', v => v.entry = {}],
['recurso ajeno', v => recurso(v).resourceType = 'Observation'],
['no simulado', v => delete recurso(v).meta],
['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'],
['sin id', v => delete recurso(v).id],
['estado desconocido', v => recurso(v).status = 'amended'],
['estado anulado', v => recurso(v).status = 'entered-in-error'],
['otra paciente', v => recurso(v).subject.reference = 'Patient/43'],
['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'],
['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'],
['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'],
['sin modelo', v => delete recurso(v).method],
['modelo sin versión', v => delete recurso(v).method.coding[0].version],
['sin predicciones', v => recurso(v).prediction = []],
['predicción nula', v => recurso(v).prediction[0] = null],
['sin desenlace', v => delete recurso(v).prediction[0].outcome],
['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'],
['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01],
['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01],
['sin periodo', v => delete recurso(v).prediction[0].whenPeriod],
['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'],
['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'],
['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'],
['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'],
['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }],
['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07],
['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'],
];
it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => {
const entrada = riesgoCacuEjemplo(); mutar(entrada);
expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida');
expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida');
});
it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => {
expect(() => riesgoPacienteResponse(entrada)).toThrow();
@@ -1,54 +1,104 @@
import { isoDate } from '../cacu-seguimiento.models';
import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
const nullableNumber = (v: unknown) => v === null || finite(v);
const nullableText = (v: unknown) => v === null || typeof v === 'string';
const text = (v: unknown) => typeof v === 'string';
const estado = (v: unknown) => v === 'preliminary' || v === 'final';
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final';
const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo'];
const DAYS_PER_YEAR = 365.25;
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
const SIMULATED = 'simulado';
function utcTimestamp(v: unknown) {
function utcTimestamp(v: unknown): v is string {
return typeof v === 'string'
&& /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v)
&& isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v));
}
function cohorteValida(v: unknown) {
return v === null || record(v)
&& v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice'])
&& (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string))
&& nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r'])
&& nullableText(v['pap_0']) && nullableText(v['hpv_0']);
function invalid(): never {
throw new Error('Respuesta de riesgo individual DEV inválida');
}
function horizonteValido(v: unknown) {
if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false;
for (const key of ['ic_bajo', 'ic_alto']) {
if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false;
/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */
function years(start: string, end: string): number {
const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000;
return Math.round(days / DAYS_PER_YEAR * 100) / 100;
}
function interval(prediction: Record<string, unknown>): { ic_bajo: number | null; ic_alto: number | null } {
const extensions = prediction['extension'];
if (extensions === undefined) return { ic_bajo: null, ic_alto: null };
if (!Array.isArray(extensions)) invalid();
const found = extensions.find(e => record(e) && e['url'] === INTERVAL);
if (found === undefined) return { ic_bajo: null, ic_alto: null };
const range = found['valueRange'];
const low = record(range) && record(range['low']) ? range['low']['value'] : undefined;
const high = record(range) && record(range['high']) ? range['high']['value'] : undefined;
if (!probability(low) || !probability(high) || low > high) invalid();
return { ic_bajo: low, ic_alto: high };
}
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
const period = prediction['whenPeriod'];
if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid();
const from = period['start'] as string, to = period['end'] as string;
if (start !== undefined && from !== start) invalid(); // one index date per patient
const h = years(from, to);
if (h < 0) invalid();
const ic = interval(prediction);
const p = prediction['probabilityDecimal'];
if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid();
return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from };
}
function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status'])
|| !utcTimestamp(v['occurrenceDateTime'])) invalid();
const subject = v['subject'];
if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/')
|| (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid();
const method = v['method'];
const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined;
if (!record(model) || !text(model['code']) || !text(model['version'])) invalid();
const predictions = v['prediction'];
if (!Array.isArray(predictions) || predictions.length === 0) invalid();
let start: string | undefined;
const horizontes: HorizonteRiesgoCacu[] = [];
for (const prediction of predictions) {
const found = horizon(prediction, start);
start = found.start;
horizontes.push(found.horizonte);
}
// Missing/null endpoints are preserved. A complete interval must contain the probability.
return !(probability(v['ic_bajo']) && probability(v['ic_alto']))
|| v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto'];
horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios);
if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid();
const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding'])
? predictions[0]['outcome']['coding'][0] : undefined;
if (!record(outcome) || !text(outcome['code'])) invalid();
return {
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
horizontes,
};
}
function riesgoValido(v: unknown) {
if (v === null) return true;
if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version'])
|| !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false;
const horizontes = v['horizontes'];
return horizontes.every(horizonteValido)
&& horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']);
function simulated(resource: Record<string, unknown>): boolean {
const meta = resource['meta'];
return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED);
}
/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */
export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu {
if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) {
throw new Error('Respuesta de riesgo individual DEV inválida');
}
return structuredClone(v) as unknown as RiesgoPacienteCacu;
/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only).
* `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */
export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null {
if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid();
const entries = v['entry'] ?? [];
if (!Array.isArray(entries)) invalid();
if (entries.length === 0) return null;
const resource = record(entries[0]) ? entries[0]['resource'] : undefined;
if (!record(resource) || !simulated(resource)) invalid();
return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) };
}
/** Presentation helper: an incomplete interval must never become a fabricated range. */
@@ -4,6 +4,7 @@ import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { clasificacionHistologica } from './mapeo-histologico';
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
@@ -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>[])) {
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;
}
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
* 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>
<div class="headline">
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ 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>
@for (dom of a.dominios; track dom.codigo) {
<div class="dominio">
@@ -37,18 +37,24 @@
</section>
<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) {
<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">
<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>
<dl>
@for (c of e.criterios_calidad; track c.codigo) {
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
@for (c of delEstudio(e); track c.codigo) {
<dt>{{ c.etiqueta }}@if (c.decisivo) {<small> (decisiva)</small>}</dt><dd [attr.data-calidad]="c.nivel">{{ valorDe(c) }}</dd>
}
</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> }
</section>
@@ -56,7 +62,7 @@
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">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.</p>
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
<ul class="metricas">
@for (m of e.alteraciones; track m.codigo) {
@@ -66,10 +72,10 @@
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
<span class="estado">{{ estado[m.estado] }}</span>
</div>
@if (m.valor !== null) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
@if (m.referencia; as r) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
} @else {
<p class="valor">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) {
<p class="efectos-titulo">Posibles efectos asociados</p>
@@ -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; }
.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; }
@@ -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; }
.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=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-calidad] { flex: none; white-space: nowrap; }
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 .azul { background: #2166AC; }
.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; }
.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); }
@@ -56,7 +55,7 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
.mapa h3 { margin-top: 0; }
@keyframes aparecer { from { opacity: 0; } }
@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); } }
@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; }
@@ -72,3 +71,5 @@ 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 { 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; }
.canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; }
@@ -2,12 +2,14 @@ import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
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,
TeaSeguimientoService, TeaAdos2,
} from './tea-seguimiento.service';
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
// 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 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 INK = '#081839';
@@ -73,7 +75,7 @@ export class TeaPacienteResumen implements OnInit {
this.mapaElegido = mapa?.codigo;
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
}
readonly clasificacion = CLASIFICACION;
readonly clasificacion = CLASIFICACIONES_ADOS2;
readonly nivelCss = NIVEL_CSS;
readonly calidad = CALIDAD;
readonly estado = ESTADO;
@@ -91,6 +93,17 @@ export class TeaPacienteResumen implements OnInit {
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'); }
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
}
@@ -6,8 +6,9 @@ import { estratoValor } from './indicadores-fhir';
import { SeguimientoQuery } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
import {
RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad,
teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse,
TeaSeguimientoService,
} from './tea-seguimiento.service';
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
@@ -19,7 +20,7 @@ interface Observation extends Resource {
valueInteger?: number; valueQuantity?: Quantity; valueString?: string; valueCodeableConcept?: Concept;
interpretation?: Concept[]; dataAbsentReason?: Concept;
referenceRange?: { low?: Quantity; high?: Quantity; text?: string }[];
component?: { code?: Concept; valueInteger?: number; valueQuantity?: Quantity; valueString?: string; 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 {
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
@@ -28,6 +29,9 @@ interface Metric { code?: string; display?: string; property?: { code: string; v
const MAX_COUNT = 200;
const METRICAS = 'tea-eeg-metrica';
// The EEG analysis's quality checks, under the code system of its own validation report.
const CRITERIOS = 'urn:tea:validation';
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
@@ -77,10 +81,16 @@ export function mapaDeElectrodos(codigo: string, etiqueta: string, valores: Reco
return { codigo, metrica: `${etiqueta} (puntuación z)`, z, regiones };
}
// The module as the page writes it: `MODULO_1` is 1, the toddler module is T.
function moduloAdos2(codigo: string | undefined): string | undefined {
const modulo = codigo?.replace(/^ados2\.modulo\./, '');
return modulo === 'TODDLER' ? 'T' : modulo?.replace(/^MODULO_/, '');
}
export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null {
const css = component(o, 'ados2.css')?.valueInteger;
if (!o?.effectiveDateTime || typeof css !== 'number') return null;
const modulo = 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 items = (o.component ?? []).filter(c => extension(c, 'dominio'));
const dominios: TeaAdosDominio[] = (o.component ?? []).filter(c => codeIn(c.code, 'ados2-dominio')).map(c => {
@@ -96,35 +106,54 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
return {
fecha: o.effectiveDateTime.slice(0, 10), modulo, algoritmo: component(o, 'ados2.algoritmo')?.valueString ?? '',
dominios, total: dominios.reduce((t, d) => t + d.puntaje, 0), total_maximo: dominios.reduce((t, d) => t + d.maximo, 0),
clasificacion: (clasificacion ?? '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'],
};
}
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
// cover the child's age (or none is in production yet).
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
const codigo = code(o.code) ?? '';
const metrica = metricas.find(m => m.code === codigo);
const 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 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;
return {
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
referencia: { min: range?.low?.value ?? 0, max: range?.high?.value ?? 0 },
valor: evaluable ? o.valueQuantity!.value! : null,
valor_z: evaluable ? component(o, 'z')?.valueQuantity?.value ?? null : null,
estado,
referencia: evaluable ? referencia : null,
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
};
}
// One quality check as the EEG analysis reports it: its value or reason, A/N, the bad channel's electrode, whether it
// alone invalidates the EEG.
function criterio(o: Observation): TeaCriterioCalidad {
const parte = (nombre: string) => o.component?.find(c => c.code?.text === nombre);
return {
codigo: codeIn(o.code, CRITERIOS)!, etiqueta: display(o.code) ?? codeIn(o.code, CRITERIOS)!,
valor: o.valueQuantity?.value ?? o.valueString ?? null, unidad: o.valueQuantity?.unit ?? '',
nivel: code(o.interpretation?.[0]) === 'A' ? 'malo' : 'bueno',
electrodo: parte('electrode')?.valueString ?? null, decisivo: parte('decisive')?.valueBoolean === true,
};
}
// The study EEG of `report`, with the observations it lists and the electrode maps of its metrics.
export function eegDeReporte(report: Report | undefined, observations: Observation[], metricas: Metric[]): TeaEeg | null {
if (!report?.effectiveDateTime) return null;
const ids = new Set((report.result ?? []).map(r => referenceId(r)));
const listed = observations.filter(o => ids.has(o.id));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'MALO').toLowerCase() as TeaNivelCalidad;
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
const duracion = extension(report, 'duracion-min')?.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>`.
const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length)))
.map(o => {
@@ -135,14 +164,10 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
.filter(m => alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'no_evaluable'));
return {
fecha: report.effectiveDateTime.slice(0, 10),
duracion_min: Math.round(extension(report, 'duracion-min')?.valueDecimal ?? 0),
canales: extension(report, 'canales')?.valueInteger ?? 0,
duracion_min: duracion === undefined ? null : Math.round(duracion),
canales: extension(report, 'canales')?.valueInteger ?? null,
calidad: calidad(report.conclusionCode?.[0]),
criterios_calidad: listed.filter(o => code(o.code)?.startsWith('eeg.calidad_')).map(o => ({
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]),
})),
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
alteraciones, mapas,
ejes_mapa: { x: EJE, y: EJE, electrodos: Object.entries(ELECTRODOS).map(([nombre, [x, y]]) => ({ nombre, x, y })) },
};
@@ -166,7 +191,7 @@ export function pacienteDeEpisodio(episode: Resource, included: Resource[], vali
const report = own.find(r => r.resourceType === 'DiagnosticReport') as Report | undefined;
const ados2 = byCode(observations, 'ados2');
const plan = own.find(r => r.resourceType === 'CarePlan') as { activity?: { detail?: { code?: Concept; status?: string } }[] } | undefined;
const modulo = code(component(ados2, 'ados2.modulo')?.valueCodeableConcept)?.replace(/^ados2\.modulo\.(MODULO_)?/, '');
const modulo = moduloAdos2(code(component(ados2, 'ados2.modulo')?.valueCodeableConcept));
return {
id_seudonimo: id,
grupo_edad: grupoEdad(extension(episode, 'grupo-edad')?.valueCoding?.code),
@@ -221,7 +246,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
const corte = query.corte ?? isoDay(this.today());
const { desde, hasta } = ventana(corte, query.meses);
let params = new HttpParams().append('date', 'ge' + desde).append('date', 'le' + hasta);
if (query.estatus) params = params.set('resultado-eeg', 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));
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);
@@ -248,6 +273,7 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
items: episodes.map(e => pacienteDeEpisodio(e, included, validadas)),
tipos_alteracion: validadas ? metricas.map(m => ({ codigo: m.code ?? '', etiqueta: m.display ?? m.code ?? '' })) : [],
resumen_eeg: {
validadas, con_eeg_valido: validadas ? parameter(resumen, 'normales') + parameter(resumen, 'anormales') : parameter(resumen, 'con_eeg_valido'),
normales: parameter(resumen, 'normales'), anormales: parameter(resumen, 'anormales'), sin_eeg: parameter(resumen, 'sin_eeg_valido'),
por_alteracion: porAlteracion(resumen, metricas),
},
@@ -261,12 +287,11 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
}).pipe(map(({ bundle, metricas }) => {
const all = resources(bundle);
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
const metric = observations.find(o => codeIn(o.code, METRICAS) && o.referenceRange?.[0]?.text);
const edad = metric?.referenceRange?.[0]?.text?.split(': ').pop();
const episode = resources(bundle, 'EpisodeOfCare')[0];
return teaPacienteDetalle({
simulado: all.length > 0 && all.every(isSimulated),
id_seudonimo: id,
grupo_edad: grupoEdad(edad),
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
}, id);
@@ -4,7 +4,8 @@ import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
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 interface TeaSeguimientoPaciente {
id_seudonimo: string;
@@ -12,7 +13,7 @@ export interface TeaSeguimientoPaciente {
ultimo_eeg: string | null;
mchat: number | null;
css_ados2: number | null;
alteraciones_eeg: AlteracionesEeg | null;
alteraciones_eeg: 'normal' | 'anormal' | null;
modulo_ados2: string | null;
estado_caso: EstadoCaso;
// What a case in process still lacks.
@@ -21,6 +22,9 @@ export interface TeaSeguimientoPaciente {
alteraciones: string[];
}
export interface TeaResumenEeg {
// Without validated alterations only the split by a valid EEG is known: `normales`, `anormales` and `por_alteracion`
// stay empty.
validadas: boolean; con_eeg_valido: number;
normales: number; anormales: number; sin_eeg: number;
por_alteracion: { codigo: string; etiqueta: string; n: number }[];
}
@@ -35,21 +39,29 @@ export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: nu
export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] }
export interface TeaAdos2 {
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
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 }
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
export type TeaNivelCalidad = 'bueno' | 'aceptable' | 'malo';
// EEG metrics against age baselines and their associated effects, both pending medical validation.
export type TeaNivelCalidad = 'bueno' | 'malo' | 'sin_analizar';
// One quality check of the EEG analysis: a study-wide rule, or a bad channel with its electrode and reason.
export interface TeaCriterioCalidad {
codigo: string; etiqueta: string; valor: number | string | null; unidad: string; nivel: 'bueno' | 'malo';
electrodo: string | null; decisivo: boolean;
}
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
export interface TeaEegAlteracion {
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number };
codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number; mediana: number | null } | null;
valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[];
// Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age.
sin_evaluar: 'sin_valor' | 'sin_referencia' | null;
}
export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] }
export interface TeaEeg {
fecha: string; duracion_min: number; canales: number;
// The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers.
calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[];
fecha: string; duracion_min: number | null; canales: number | null;
// The overall rating is the EEG analysis's verdict; its checks say why.
calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[];
alteraciones: TeaEegAlteracion[];
// One map per alteration that could be evaluated, on shared axes.
mapas: TeaEegMapa[];
@@ -57,6 +69,10 @@ export interface TeaEeg {
}
export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null }
// TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape.
export const CLASIFICACIONES_ADOS2: Record<ClasificacionAdos2, string> = {
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
preocupacion_leve_moderada: 'Preocupación leve a moderada', preocupacion_severa: 'Preocupación de moderada a severa',
};
export const ESTADOS_CASO: Record<EstadoCaso, string> = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' };
export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses'];
// M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary.
@@ -71,15 +87,22 @@ export const RANGOS_CSS = [
{ codigo: 'moderado', etiqueta: 'Nivel moderado (5–7)', min: 5, max: 7 },
{ codigo: 'alto', etiqueta: 'Nivel alto (8–10)', min: 8, max: 10 },
];
export const ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
export const ALTERACIONES_EEG: SeguimientoStatus[] = [
{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' },
];
export const EEG_VALIDO: SeguimientoStatus[] = [{ codigo: 'valido', etiqueta: 'Con EEG válido' }, { codigo: 'sin_eeg_valido', etiqueta: 'Sin EEG válido' }];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
const filtroEeg = (v: unknown) => v === null || ['normal', 'anormal', 'valido', 'sin_eeg_valido'].includes(v as string);
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
// ADOS-2 item codes: 0 to 3, and 7 to 9 for an item that doesn't apply or wasn't scored.
const CODIGOS_REACTIVO = [0, 1, 2, 3, 7, 8, 9];
const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string');
function validResumenEeg(r: unknown): boolean {
return record(r) && 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']));
}
export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
@@ -88,7 +111,7 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse {
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|| !record(filters) || !filtroEeg(filters['alteraciones_eeg'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
@@ -106,33 +129,39 @@ const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
function validAdos(a: unknown): boolean {
if (a === null) return true;
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || typeof a['algoritmo'] !== 'string' || !score(a['css'], 1, 10)
|| !(a['clasificacion'] === null || Object.hasOwn(CLASIFICACIONES_ADOS2, a['clasificacion'] as string))
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
// Items 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 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['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
}
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
// 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 {
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
const ref = a !== null && record(a) ? a['referencia'] : undefined;
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string'
|| !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number)
&& (ref['mediana'] === null || finite(ref['mediana'])))
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
const estado = a['estado'];
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string)
&& (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null);
return finite(a['valor']) && finite(a['valor_z']) && ref !== null && a['sin_evaluar'] === null
&& ['normal', 'aumentado', 'disminuido'].includes(estado as string);
}
function validEeg(e: unknown): boolean {
if (e === null) return true;
const nivel = (v: unknown) => ['bueno', 'aceptable', 'malo'].includes(v as string);
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad'])
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad'])
&& (c['unidad'] === 'canales' ? integer(c['valor']) && (c['valor'] as number) <= (e['canales'] as number) : finite(c['valor']) && (c['valor'] as number) >= 0))) return false;
const optional = (v: unknown) => v === null || integer(v);
if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales'])
|| !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string)
|| !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta'])
&& ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean'
&& (c['electrodo'] === null || text(c['electrodo'])) && (c['valor'] === null || finite(c['valor']) || text(c['valor'])))) return false;
if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false;
const ejes = e['ejes_mapa'];
if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false;
@@ -13,13 +13,14 @@ const data = {
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: [] }],
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 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 = [
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('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' }),
@@ -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',
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)] }] },
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable',
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' }],
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'bueno',
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,
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 }] } },
@@ -75,7 +80,7 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('input[type=date]')).not.toBeNull();
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
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.apply();
const filtered = request();
@@ -218,7 +223,7 @@ describe('Seguimiento TEA', () => {
const panel = root.querySelector('#tea-detalle-T-0002')!;
expect(panel.textContent).toContain('CSS 3');
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.
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
// Item scores start collapsed.
@@ -228,7 +233,7 @@ describe('Seguimiento TEA', () => {
expect(metricas.textContent).toContain('Disminuido');
expect(metricas.textContent).toContain('Posibles efectos asociados');
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
expect(metricas.textContent).toContain('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(
['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.');
@@ -269,6 +274,29 @@ describe('Seguimiento TEA', () => {
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
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', () => {
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
@@ -279,25 +307,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, 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();
request().flush(tres); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
const panel = root.querySelector('section.calidad')!;
expect(panel.querySelector('.css')!.textContent!.trim()).toBe('Aceptable');
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(panel.querySelectorAll('dd')[1].getAttribute('data-calidad')).toBe('aceptable');
expect(panel.textContent).not.toMatch(/Impedancia|Artefactos|de 100/);
const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim();
expect(texto(panel.querySelector('.css')!)).toBe('Válido');
expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']);
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 } });
expect(() => teaPacienteDetalle(conCriterios(undefined), 'T-0001')).toThrow();
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: 'canales', nivel: 'bueno' };
expect(() => teaPacienteDetalle(conCriterios([criterio]), 'T-0001')).not.toThrow();
const criterio = { codigo: 'a', etiqueta: 'A', valor: 2, unidad: '', nivel: 'bueno', electrodo: null, decisivo: false };
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, valor: null }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, valor: 20 }]), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(conCriterios([{ ...criterio, decisivo: 'si' }]), '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: 'sin_analizar', duracion_min: null, canales: null } }, 'T-0001')).not.toThrow();
http.verify();
});
it('valida las alteraciones del EEG', () => {
@@ -306,6 +336,8 @@ describe('Seguimiento TEA', () => {
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), '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, 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], efectos: [''] }), 'T-0001')).toThrow();
expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow();
@@ -1,7 +1,7 @@
<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>
<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="tabs" aria-label="Secciones de TEA">
<header><h1>Trastorno del espectro autista</h1><p>Explora los indicadores de trastorno del espectro autista.</p></header>
<nav class="domain-nav" aria-label="Dominios de indicadores"><a routerLink="/indicadores/cacu">Cáncer cervicouterino</a><a routerLink="/indicadores/cama">Cáncer de mama</a><a routerLink="/indicadores/tea" aria-current="page">Trastorno del espectro autista</a></nav>
<nav class="tabs" aria-label="Secciones de trastorno del espectro autista">
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Resumen</button>
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Histórico</button>
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
@@ -61,7 +61,7 @@
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
@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>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> }
}
</section>
@@ -1,5 +1,4 @@
.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 a { color: #216b56; padding: .5rem; }
.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'); }
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'; }
qualityStatus(observation: Resource) { const value = code(observation.interpretation?.[0]); return value === 'BUENO' ? 'buena' : value === 'MALO' ? 'mala' : '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}`) && code(r.code).startsWith('eeg.calidad_')); }
// The EEG analysis's checks: A is out of range, N within.
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-')); }
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'); }
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-3: var(--space-3);
--issste-space-4: var(--space-4);
--issste-space-5: var(--space-5);
--issste-space-6: var(--space-6);
--issste-radius: var(--mat-sys-corner-medium);
}