From 2cbb9946677d9de7ec65d3efe6af2729dc5492d3 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 29 Oct 2026 02:38:43 +0000 Subject: [PATCH 01/20] feat(tea): seguimiento con resumen por paciente y resumen por periodo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Pestaña Seguimiento de TEA: tabla de pacientes con filtro de alteraciones EEG y fila desplegable con ADOS-2 por reactivo, calidad del EEG y mapa topográfico (GET /tea/seguimiento/). - Indicadores destacados: M21 y M22 (pacientes con TEA con y sin EEG). - Con un solo periodo elegido, TEA muestra un párrafo de resumen en lugar de las tarjetas. --- .../indicadores/cacu-seguimiento.spec.ts | 2 +- .../indicadores/indicador-kpi-panel.spec.ts | 15 +- .../indicadores-initial-integration.spec.ts | 30 ++-- .../indicadores/indicadores-kpi.spec.ts | 7 +- .../features/indicadores/indicadores-kpi.ts | 12 +- .../indicadores/indicadores-page.html | 7 +- .../indicadores/indicadores-page.scss | 1 + .../features/indicadores/indicadores-page.ts | 9 +- .../indicadores/indicadores-sections.spec.ts | 7 +- .../indicadores/indicadores-tracking.html | 32 ++++- .../indicadores/indicadores-tracking.scss | 10 ++ .../indicadores/indicadores-tracking.ts | 45 ++++-- .../indicadores-visibility.spec.ts | 3 + .../paciente-detalle/paciente-detalle.spec.ts | 2 + .../indicadores/tea-paciente-resumen.html | 73 ++++++++++ .../indicadores/tea-paciente-resumen.scss | 29 ++++ .../indicadores/tea-paciente-resumen.ts | 70 +++++++++ .../indicadores/tea-resumen-periodo.spec.ts | 55 ++++++++ .../indicadores/tea-resumen-periodo.ts | 62 ++++++++ .../indicadores/tea-seguimiento.service.ts | 110 +++++++++++++++ .../indicadores/tea-seguimiento.spec.ts | 133 ++++++++++++++++++ 21 files changed, 677 insertions(+), 37 deletions(-) create mode 100644 src/app/features/indicadores/tea-paciente-resumen.html create mode 100644 src/app/features/indicadores/tea-paciente-resumen.scss create mode 100644 src/app/features/indicadores/tea-paciente-resumen.ts create mode 100644 src/app/features/indicadores/tea-resumen-periodo.spec.ts create mode 100644 src/app/features/indicadores/tea-resumen-periodo.ts create mode 100644 src/app/features/indicadores/tea-seguimiento.service.ts create mode 100644 src/app/features/indicadores/tea-seguimiento.spec.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index f3c85c8..ff2a6ac 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -92,7 +92,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow(); open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); }); - it.each(['tea','cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => { + it.each(['cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => { fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true); expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible'); expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.'); diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 4c274ce..5a257c2 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -27,9 +27,14 @@ describe('KPI integración con autoridad global', () => { if (!initial) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain); fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }))); - for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) }); + flushPeriodos(() => periods.map(periodo => ({ tipo: 'semestre', periodo }))); fixture.detectChanges(); } + // Availability runs four requests at a time; flushing one batch starts the next. + function flushPeriodos(periodos: () => unknown[]) { + for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos'))) + pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() })); + } // Regression assertions below target the original KPI contracts. The added lab // consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts. // Satisfy its independent request with an explicit empty response, never diagnosis data. @@ -56,7 +61,7 @@ describe('KPI integración con autoridad global', () => { expect(panels().map(p => p.definition.id)).toEqual([]); expect(panels().every(p => p.result().state === 'Esperando filtro aplicado')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); }); - it('TEA consulta sus tres destacados y muestra conteo, porcentaje y mediana', () => { + it('TEA consulta sus cinco destacados y muestra conteo, porcentajes y mediana', () => { fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush([]); load('tea'); const initial = requests(); expect(initial.map(r => r.request.url)).toEqual(['/tea/indicadores/' + KPI_BY_DOMAIN.tea[0].id + '/datos']); @@ -64,8 +69,10 @@ describe('KPI integración con autoridad global', () => { const req = requests(); expect(req.map(r => r.request.url)).toEqual(KPI_BY_DOMAIN.tea.slice(1).map(d => '/tea/indicadores/' + d.id + '/datos')); req.forEach((r, i) => r.flush(response(i + 1, 'tea'))); fixture.detectChanges(); - expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7]]); + expect(panels().map(p => [p.result().state, p.result().value])).toEqual([['Disponible', 5], ['Disponible', '40.0'], ['Disponible', 7], ['Disponible', '40.0'], ['Disponible', '40.0']]); expect(panels()[1].result().info).toContain('2 de 5 pacientes con nota médica con diagnóstico CIE-10 F84.0.'); + expect(panels()[3].result().info).toBe('2 de 5 pacientes con TEA positivo tienen un EEG ligado.'); + expect(panels()[4].result().info).toBe('2 de 5 pacientes con TEA positivo no tienen ningún EEG ligado.'); }); it('dos KPI reales y un placeholder manejan 404, error y éxito sin cifras anteriores', () => { load('cacu'); const req = requests(); expect(req).toHaveLength(2); expect(panels().every(p => p.result().loading)).toBe(true); @@ -164,7 +171,7 @@ describe('KPI integración con autoridad global', () => { TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu'); fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] }))); - http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges(); + flushPeriodos(() => []); fixture.detectChanges(); expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); }); diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 8671c65..46debeb 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -33,9 +33,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid http = TestBed.inject(HttpTestingController); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); - const inventory = http.match(r => r.url.endsWith('/periodos')); - expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request. - inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) })); + // The anchor shares the catalog inventory request; availability runs four at a time. + expect(flushPeriodos(() => [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })))).toBe(items.length); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); @@ -45,6 +44,13 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid periodo: period, grupo: d.contrato === 'C1' && domain !== 'tea' ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: value, suprimido: 0, valor: 50, numerador: 5, denominador: 10, mediana: 2, q1: 1, q3: 3, unidad: 'dias' }] }; } + function flushPeriodos(periodos: () => unknown[]) { + let flushed = 0; + for (let pending = http.match(r => r.url.endsWith('/periodos')); pending.length; pending = http.match(r => r.url.endsWith('/periodos'))) { + pending.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: periodos() })); flushed += pending.length; + } + return flushed; + } function request(period: string) { return http.expectOne(r => r.url.endsWith(`/${definitions[0].id}/datos`) && r.params.get('periodos') === period); } // Regression assertions below target the original KPI contracts. The added lab // consumer has complete contract/transport coverage in indicadores-kpi-resultado.spec.ts. @@ -60,11 +66,15 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); } 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) { - const requests = originalRequests(); - expect(requests).toHaveLength(expected); - requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); - const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); }); + let flushed = 0; + for (let requests = originalRequests(); requests.length; requests = originalRequests()) { + requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(period); + const index = definitions.findIndex(d => r.request.url.endsWith(`/${d.id}/datos`)); r.flush(data(index, period)); }); + flushed += requests.length; + } + expect(flushed).toBe(expected); fixture.detectChanges(); } function choose() { @@ -79,7 +89,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const ongoing = request(periods[0]); for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { page.changeSection(section); fixture.detectChanges(); - for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); + for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.initialPeriodState()).toBe('loading'); expect(ongoing.cancelled).toBe(false); http.expectNone(() => true); @@ -99,7 +109,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid editor().select([periods[2]]); fixture.detectChanges(); for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { page.changeSection(section); fixture.detectChanges(); - for (const req of http.match(r => r.url === '/cacu/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); + for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(editor().selectedPeriods).toEqual([periods[2]]); expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g'); @@ -221,7 +231,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const catalog = definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f'] })); catalogs.set(target, catalog); page.changeDominio(target); http.expectOne('/' + target + '/indicadores').flush(catalog); fixture.detectChanges(); - http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: period, tipo: 'semestre' }] })); + flushPeriodos(() => [{ periodo: period, tipo: 'semestre' }]); const payload = (index: number) => { const value = data(0, period); value.id = definitions[index].id; value.contrato = definitions[index].contrato; value.filas[0].grupo = definitions[index].contrato === 'C1' && target !== 'tea' ? 'total' : 'TOTAL'; return value; diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index 9b612f7..9c01682 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -55,9 +55,12 @@ it('categorías incompletas nunca producen un total parcial', () => { expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined(); }); -it('TEA usa sus tres indicadores destacados y su grupo C1 es TOTAL', () => { +it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => { expect(KPI_BY_DOMAIN.tea.map(d => [d.id, d.contrato])).toEqual([ - ['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r']]); + ['M23_pacientes_evaluados', 'C2'], ['M24_confirmacion_diagnostico', 'C1'], ['M25_dias_mchat_diagnostico', 'C3r'], + ['M21_diagnosticados_con_eeg', 'C1'], ['M22_diagnosticados_sin_eeg', 'C1']]); + const eeg = data('tea', 3, [{ ...total, grupo: 'TOTAL', valor: 62.3, numerador: 71, denominador: 114 }]); + expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con TEA positivo tienen un EEG ligado.'); const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]); expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0', info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' }); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 9985a79..33aed03 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -2,7 +2,11 @@ import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; import { percentNumber } from './indicadores-format'; -export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; } +export interface KpiDefinition { + id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; + // C1 only: replaces the domain's explanatory line when the numerator is not the domain's usual one. + c1Info?: (numerador: number, denominador: number) => string; +} // Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID. 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, @@ -16,6 +20,10 @@ export const KPI_BY_DOMAIN: Record = { { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, { id: 'M24_confirmacion_diagnostico', title: 'Porcentaje de confirmación diagnóstica', contrato: 'C1', unit: '%' }, { id: 'M25_dias_mchat_diagnostico', title: 'Tiempo de aplicación de M-CHAT (psicología) a diagnóstico positivo', contrato: 'C3r', unit: 'días (mediana)' }, + { id: 'M21_diagnosticados_con_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unit: '%', + c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo tienen un EEG ligado.` }, + { id: 'M22_diagnosticados_sin_eeg', title: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1', unit: '%', + c1Info: (n, d) => `${n} de ${d} pacientes con TEA positivo no tienen ningún EEG ligado.` }, ], cacu: [ { id: 'cacu_eu7', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' }, @@ -78,7 +86,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; - return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) }; + return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(row['numerador'], row['denominador']) }; } if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index ece0cad..bb00b0c 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -76,8 +76,11 @@ @let kpis = opportunityKpis; @if (kpis.length && !initialPeriodBlocked) {
-

{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}

-
+ @let resumen = teaResumenPeriodo; +

{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}

+ @if (resumen) { } + +
@for (definition of kpis; track dominio + ':' + definition.id) { diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index c3f0285..ef586aa 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -41,6 +41,7 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .kpi-section, .graphic-section { min-width: 0; } .graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); } .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; } .catalog-grid { align-items: stretch; } .catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; } .catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); } diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index b42015b..30254e3 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -18,6 +18,7 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; +import { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; @@ -33,7 +34,7 @@ type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, TeaResumenPeriodo], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -93,6 +94,7 @@ export class IndicadoresPage { readonly navigationItems = computed(() => this.searchResults().items.map(item => ({ key: indicatorIdentity(this.dominio, item.id), titulo: item.titulo }))); private readonly graphicCards = viewChildren(IndicadorCatalogCard); + readonly kpiPanels = viewChildren(IndicadorKpiPanel); private readonly observedRegions = new Map(); private renderedCards: readonly IndicadorCatalogCard[] = []; private visibilityObserver?: IntersectionObserver; @@ -290,6 +292,11 @@ export class IndicadoresPage { return undefined; } 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. + get teaResumenPeriodo(): string | undefined { + const selection = this.filters?.applied.selection; + return this.dominio === 'tea' && selection?.mode === 'explicit' && selection.periodos.length === 1 ? selection.periodos[0] : undefined; + } get opportunityKpis() { const definitions = this.availableKpis; if (this.dominio !== 'cacu' || (!definitions.length && !this.catalog().some(item => item.id === CACU_RESULTADO_KPI.id))) return definitions; diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 7ce6cb3..f518dff 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -51,8 +51,8 @@ describe('Secciones compartidas por dominio', () => { } const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance); tabs[1].click(); harness.detectChanges(); - if (domain === 'cacu') { - http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); + if (domain === 'cacu' || domain === 'tea') { + http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); } const tracking = root.querySelector('#panel-seguimiento')!; @@ -61,6 +61,9 @@ describe('Secciones compartidas por dominio', () => { if (domain === 'cacu') { expect(tracking.querySelector('tbody')).toBeNull(); expect(tracking.querySelector('input[type=date]')).not.toBeNull(); + } else if (domain === 'tea') { + expect(tracking.querySelector('tbody')).toBeNull(); + expect(tracking.querySelector('input[type=date]')).not.toBeNull(); } else { expect(tracking.querySelectorAll('thead th')).toHaveLength(6); expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 82e4f1d..d3fe8d0 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -5,7 +5,7 @@ }

Seguimiento de {{ domainLabel }}

-@if (dominio !== 'cacu') { +@if (dominio !== 'cacu' && dominio !== 'tea') {

El seguimiento aún no está disponible.

@@ -19,8 +19,8 @@ -
+ + + + @for (item of response.items; track item.id_seudonimo) { + + + + + @if (teaAbierto === item.id_seudonimo) { + + } + } @empty { } + +
Resultados disponibles por paciente
Identificador seudónimoGrupo de edadÚltimo EEGPuntaje M-CHATCSS ADOS-2Alteraciones EEG
{{ item.grupo_edad }}{{ item.ultimo_eeg ?? 'No disponible' }}{{ item.mchat ?? 'No disponible' }}{{ item.css_ados2 ?? 'No disponible' }}@if (item.alteraciones_eeg; as eeg) { {{ eeg === 'anormal' ? 'Anormal' : 'Normal' }} } @else { No disponible }
No hay registros para los filtros aplicados.
+
+ } @else if (data; as response) {
@@ -51,6 +73,8 @@
Resultados disponibles por paciente
+ } + @if (response; as response) {
@if (d.eeg; as e) { +

Alteraciones del EEG Datos de ejemplo

-

Rangos de referencia y efectos asociados de ejemplo, pendientes de validación médica.

+

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.

@if (!alteradas(e).length) {

Sin alteraciones en las métricas evaluadas.

}
    @for (m of e.alteraciones; track m.codigo) {
  • - {{ m.etiqueta }} + {{ estado[m.estado] }}
    @if (m.valor !== null) { @@ -80,19 +82,23 @@
-
-

Zonas más afectadas

-

{{ e.mapa.metrica }} · mapa ilustrativo

- @if (figura) { - - } -
    - @for (r of e.regiones; track r.codigo) { -
  1. {{ r.etiqueta }}z = {{ r.valor_z }}
  2. + @if (mapaActual(e); as mapa) { +
    +

    Zonas más afectadas

    +

    {{ mapa.metrica }} · mapa ilustrativo

    +

    Azul: menos actividad Rojo: más actividad

    + @if (figura) { + } -
-
+
    + @for (r of mapa.regiones; track r.codigo) { +
  1. {{ r.etiqueta }}z = {{ r.valor_z }}
  2. + } +
+
+ } + } } diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 9e0a85a..6826e0b 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -13,6 +13,16 @@ h3 { margin: 0 0 .15rem; font-size: 1rem; } .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; } +// The button's area covers its whole card, so the card is clickable without nesting the effects list in a button. +button.nombre { margin: 0; min-height: 0; padding: 0; border: 0; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; } +button.nombre::after { content: ''; position: absolute; inset: 0; border-radius: inherit; } +button.nombre:disabled { cursor: default; } +button.nombre:focus-visible { outline: none; } +button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outline-offset: 2px; } +.leyenda-mapa { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; margin: .25rem 0; font-size: .8rem; } +.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; } @@ -38,7 +48,21 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; } .sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; } .metricas, .efectos { margin: 0; padding: 0; list-style: none; } -.metricas > li { padding: .4rem 0 .4rem .6rem; border-top: 1px solid var(--issste-border); border-inline-start: 4px solid transparent; } +// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it. +.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; } +.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; } +.marco-mapa { min-width: 0; overflow: hidden; } +.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; } +.mapa h3 { margin-top: 0; } +@keyframes aparecer { from { opacity: 0; } } +@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } } +@container zona (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; } +.metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; } +.metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); } +.metricas > li:has(button[aria-expanded=true]) { border-color: var(--issste-accent); background: color-mix(in srgb, var(--issste-accent) 12%, transparent); } .metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; } .metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; } li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 50d25d7..1170859 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -1,8 +1,8 @@ -import { Component, DestroyRef, inject, Input, OnInit, signal } from '@angular/core'; +import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; -import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service'; +import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service'; const CLASIFICACION: Record = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' }; // ADOS-2 calibrated severity score ranges. @@ -14,17 +14,17 @@ const INK = '#081839'; // Shape paths have no arcs: the hole is a polygon, wound against the frame so it stays empty under either fill rule. const HOLE = Array.from({ length: 96 }, (_, i) => -2 * Math.PI * i / 96) .map((a, i) => `${i ? 'L' : 'M'} ${Math.cos(a).toFixed(4)} ${Math.sin(a).toFixed(4)}`).join(' '); -// A white frame with a round hole hides the map outside the head; then the head outline, nose and ears. -const HEAD_SHAPES = [ - { type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: '#FFFFFF', line: { width: 0 } }, +// A frame with a round hole hides the map outside the head, in the colour behind the map; then the head outline, nose and ears. +const headShapes = (fondo: string) => [ + { type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: fondo, line: { width: 0 } }, { type: 'circle', xref: 'x', yref: 'y', x0: -1, y0: -1, x1: 1, y1: 1, line: { color: INK, width: 2 } }, { type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line: { color: INK, width: 2 } }, { type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line: { color: INK, width: 2 } }, { type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line: { color: INK, width: 2 } }, ]; -export function mapaFigure(eeg: TeaEeg): PlotlyFigure { - const m = eeg.mapa; +export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): PlotlyFigure { + const m = { ...eeg.ejes_mapa, z: mapa.z }; return { data: [ { type: 'contour', x: m.x, y: m.y, z: m.z, zmin: -3, zmax: 3, zmid: 0, colorscale: 'RdBu', connectgaps: false, @@ -34,7 +34,7 @@ export function mapaFigure(eeg: TeaEeg): PlotlyFigure { textposition: 'top center', textfont: { size: 9, color: INK }, marker: { size: 5, color: INK }, hoverinfo: 'text', showlegend: false }, ], layout: { - margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: HEAD_SHAPES, + margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: headShapes(fondo), paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', xaxis: { visible: false, range: [-1.2, 1.2], fixedrange: true }, yaxis: { visible: false, range: [-1.15, 1.2], scaleanchor: 'x', fixedrange: true }, @@ -51,12 +51,28 @@ export function mapaFigure(eeg: TeaEeg): PlotlyFigure { }) export class TeaPacienteResumen implements OnInit { @Input({ required: true }) id = ''; - // In its own window there is room for two wide columns instead of four narrow ones. private readonly service = inject(TeaSeguimientoService); private readonly destroy = inject(DestroyRef); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); readonly detalle = signal(undefined); figura?: PlotlyFigure; + private mapaElegido?: string; + private readonly elemento = inject>(ElementRef); + // The first solid background around this component: the map has no box of its own. + private fondo() { + for (let e: HTMLElement | null = this.elemento.nativeElement; e; e = e.parentElement) { + const color = getComputedStyle(e).backgroundColor; + if (/^rgb\(/.test(color)) return color; + } + return '#FFFFFF'; + } + mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); } + elegirMapa(eeg: TeaEeg, codigo: string) { + // The chosen card closes the map again, and the cards take the whole space back. + const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo); + this.mapaElegido = mapa?.codigo; + this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + } readonly clasificacion = CLASIFICACION; readonly nivelCss = NIVEL_CSS; readonly calidad = CALIDAD; @@ -65,7 +81,7 @@ export class TeaPacienteResumen implements OnInit { load() { this.status.set('loading'); this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ - next: d => { this.figura = d.eeg ? mapaFigure(d.eeg) : undefined; this.detalle.set(d); this.status.set('ready'); }, + next: d => { this.mapaElegido = undefined; this.figura = undefined; this.detalle.set(d); this.status.set('ready'); }, error: () => this.status.set('error'), }); } diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts index 7e4ae2a..b0dd516 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts @@ -3,7 +3,7 @@ import { TestBed } from '@angular/core/testing'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; -type Result = { state: string; value?: string | number; loading?: boolean; period?: string }; +type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record }; function panel(id: string, result: Result) { return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType>; retry: ReturnType }; } @@ -16,18 +16,19 @@ describe('Resumen TEA por periodo', () => { fixture.detectChanges(); return fixture; } - const completos = () => [panel('M23_pacientes_evaluados', listo(409)), panel('M24_confirmacion_diagnostico', listo('86.5')), - panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1'))]; + const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { COMPLETO: 60, EN_PROCESO: 25, FUERA_PROTOCOLO: 15 } }), panel('M24_confirmacion_diagnostico', listo('86.5')), + panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')), + panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))]; it('redacta el párrafo con cada población y resalta los valores', () => { const root: HTMLElement = render(completos()).nativeElement; const text = root.textContent!.replace(/\s+/g, ' '); - expect(text).toContain('En el periodo 2025-S2, 409 pacientes evaluados por psicología tuvieron un diagnóstico confirmado o en proceso.'); + expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 casos iniciados hasta entonces, 60 están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG), 25 siguen en proceso y 15 quedaron fuera del protocolo.'); expect(text).toContain('De los pacientes con nota médica, 86.5 % tuvo diagnóstico positivo de TEA (CIE-10 F84.0).'); - expect(text).toContain('hasta el diagnóstico positivo de TEA fue de 22 días.'); + expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.'); expect(text).toContain('De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), 71.9 % tenían EEG y 28.1 % no lo tenían.'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())) - .toEqual(['2025-S2', '409', '86.5 %', '22 días', '71.9 %', '28.1 %']); + .toEqual(['2025-S2', '100', '60', '25', '15', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']); expect(root.querySelector('button')).toBeNull(); }); diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts index b87c093..4f6e0c7 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.ts @@ -7,16 +7,19 @@ interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; deta // TEA summary for one explicit period. It reads the results of the (hidden) KPI panels, so the // requests, contract checks and suppression rules stay those of the cards. Each sentence names -// its own population: M23, M24, M25 and M21/M22 do not count the same patients. +// its own population: M28, M24, M25 and M21/M22 do not count the same patients. @Component({ selector: 'app-tea-resumen-periodo', imports: [MatButtonModule, NgTemplateOutlet], template: `

- En el periodo {{ periodo }}, - pacientes evaluados por psicología tuvieron un diagnóstico confirmado o en proceso. De los pacientes con nota médica, - tuvo diagnóstico positivo de TEA (CIE-10 F84.0). La mediana del tiempo desde la aplicación del M-CHAT por psicología hasta el diagnóstico positivo de TEA fue de + Al cierre del periodo {{ periodo }}, de los casos iniciados hasta entonces, + están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG), + siguen en proceso y quedaron fuera del protocolo. + De los pacientes con nota médica, + tuvo diagnóstico positivo de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de , de ADOS-2 a diagnóstico, de + , y en total, de M-CHAT a diagnóstico, de . De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), tenían EEG y no lo tenían. @@ -56,6 +59,13 @@ export class TeaResumenPeriodo { return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state }; return { texto: result.value + sufijo, estado: 'listo' }; } + // One status of M28, under the same rules as valor(). + caso(categoria: string): Valor { + const base = this.valor('M28_casos_por_estado', ''); + if (base.estado !== 'listo') return base; + const n = this.panel('M28_casos_por_estado')?.result().categorias?.[categoria]; + return n === undefined ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Estado no publicado' } : { texto: String(n), estado: 'listo' }; + } get cargando() { return this.paneles.some(p => p.result().loading); } get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); } reintentar() { this.conError.forEach(p => p.retry()); } diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 619df74..dedc1fc 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -5,6 +5,7 @@ import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } fro import { validSeguimientoQuery } from './cacu-seguimiento.service'; export type AlteracionesEeg = 'normal' | 'anormal'; +export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo'; export interface TeaSeguimientoPaciente { id_seudonimo: string; grupo_edad: string; @@ -12,10 +13,23 @@ export interface TeaSeguimientoPaciente { mchat: number | null; css_ados2: number | null; alteraciones_eeg: AlteracionesEeg | null; + modulo_ados2: string | null; + estado_caso: EstadoCaso; + // What a case in process still lacks. + pendientes: string[]; + // Codes of the alterations found. + alteraciones: string[]; +} +export interface TeaResumenEeg { + normales: number; anormales: number; sin_eeg: number; + por_alteracion: { codigo: string; etiqueta: string; n: number }[]; } export interface TeaSeguimientoResponse extends Pick { filtros: { alteraciones_eeg: AlteracionesEeg | null }; items: TeaSeguimientoPaciente[]; + tipos_alteracion: { codigo: string; etiqueta: string }[]; + // Of every patient that matches the filters, not only this page's. + resumen_eeg: TeaResumenEeg; } export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: number; puntaje_algoritmo: number } export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] } @@ -31,16 +45,19 @@ export interface TeaEegAlteracion { codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number }; valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[]; } +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 }[]; - regiones: TeaEegRegion[]; alteraciones: TeaEegAlteracion[]; - mapa: { metrica: string; x: number[]; y: number[]; z: (number | null)[][]; electrodos: { nombre: string; x: number; y: number }[] }; + // One map per alteration that could be evaluated, on shared axes. + mapas: TeaEegMapa[]; + ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] }; } 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 ESTADOS_CASO: Record = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' }; export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses']; // M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary. export const RANGOS_MCHAT = [ @@ -60,6 +77,11 @@ const record = (v: unknown): v is Record => !!v && typeof v === const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal'; const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max; +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']) + && r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n'])); +} export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse { // Same rule as CaCu: demonstration records only. if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); @@ -72,7 +94,10 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse { && typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string' && (item['ultimo_eeg'] === null || isoDate(item['ultimo_eeg'])) && score(item['mchat'], 0, 20) && score(item['css_ados2'], 1, 10) - && eeg(item['alteraciones_eeg']))) + && eeg(item['alteraciones_eeg']) && (item['modulo_ados2'] === null || typeof item['modulo_ados2'] === 'string') + && Object.hasOwn(ESTADOS_CASO, item['estado_caso'] as string) && textos(item['pendientes']) && textos(item['alteraciones'])) + || !Array.isArray(v['tipos_alteracion']) || !v['tipos_alteracion'].every(t => record(t) && typeof t['codigo'] === 'string' && typeof t['etiqueta'] === 'string') + || !validResumenEeg(v['resumen_eeg'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as TeaSeguimientoResponse; } @@ -108,14 +133,15 @@ function validEeg(e: unknown): boolean { 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']) && integer(c['valor']) && (c['unidad'] !== 'canales' || (c['valor'] as number) <= (e['canales'] as number)))) return false; - const mapa = e['mapa']; - if (!Array.isArray(e['regiones']) || !e['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))) return false; if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false; - if (!record(mapa) || !text(mapa['metrica']) || !Array.isArray(mapa['x']) || !Array.isArray(mapa['y']) || !Array.isArray(mapa['z'])) return false; - const x = mapa['x'], y = mapa['y'], z = mapa['z']; - return x.every(finite) && y.every(finite) && z.length === y.length - && z.every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) - && Array.isArray(mapa['electrodos']) && mapa['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y'])); + const ejes = e['ejes_mapa']; + if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false; + const x = ejes['x'], y = ejes['y']; + return x.every(finite) && y.every(finite) + && Array.isArray(ejes['electrodos']) && ejes['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y'])) + && e['mapas'].every(m => record(m) && text(m['codigo']) && text(m['metrica']) && Array.isArray(m['z']) && m['z'].length === y.length + && m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) + && Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))); } export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle { if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); @@ -137,6 +163,8 @@ export class TeaSeguimientoService { const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css); if (mchat) params = params.set('mchat_min', mchat.min).set('mchat_max', mchat.max); if (css) params = params.set('css_min', css.min).set('css_max', css.max); + if (query.estado_caso) params = params.set('estado_caso', query.estado_caso); + if (query.alteracion) params = params.set('alteracion', query.alteracion); return this.http.get('/tea/seguimiento', { params }).pipe(map(teaSeguimientoResponse)); } detalle(id: string) { diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index b4f8cb5..68f907f 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -1,15 +1,19 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { teaPacienteDetalle, teaSeguimientoResponse } from './tea-seguimiento.service'; +import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service'; +import { mapaFigure } from './tea-paciente-resumen'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; import { IndicadoresTracking } from './indicadores-tracking'; -const item = { id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal' }; +const item = { id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal', + modulo_ados2: '2', estado_caso: 'en_proceso', pendientes: ['Neuropediatría'], alteraciones: ['ritmo_posterior'] }; const data = { simulado: true, corte: '2026-09-30', ventana: { meses: 3, desde: '2026-07-01', hasta: '2026-09-30' }, filtros: { alteraciones_eeg: null }, 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 }], + 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 }] }, }; 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 }); @@ -20,6 +24,7 @@ const alteraciones = [ 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' }), ]; +const mapa = (codigo: string, metrica: string, region: string) => ({ codigo, metrica, z: [[null, 1, null], [0, 2.1, 0], [null, 1, null]], regiones: [{ codigo: 'r', etiqueta: region, valor_z: 2.1 }] }); const detalle = { simulado: true, id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', 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', @@ -27,8 +32,9 @@ const detalle = { { 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' }], - regiones: [{ codigo: 'central', etiqueta: 'Central', valor_z: 2.1 }], alteraciones, - mapa: { metrica: 'Potencia theta relativa (puntuación z)', x: [-1, 0, 1], y: [-1, 0, 1], z: [[null, 1, null], [0, 2.1, 0], [null, 1, null]], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } }, + 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 }] } }, }; const anormal = { ...data, filtros: { alteraciones_eeg: 'anormal' }, paginacion: { ...data.paginacion, total_items: 1 }, items: [item] }; @@ -46,16 +52,16 @@ describe('Seguimiento TEA', () => { return fixture; } const request = () => http.expectOne(r => r.url === '/tea/seguimiento'); - it('muestra las seis columnas y los valores ausentes como No disponible', () => { + it('muestra las siete columnas y los valores ausentes como No disponible', () => { const fixture = open(); request().flush(data); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; expect(Array.from(root.querySelectorAll('thead th')).map(th => th.textContent)).toEqual( - ['Identificador seudónimo', 'Grupo de edad', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']); + ['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']); const rows = root.querySelectorAll('tbody tr'); expect(rows).toHaveLength(2); expect(rows[0].textContent).toContain('Anormal'); - expect(rows[1].querySelectorAll('td')[2].textContent).toContain('No disponible'); + expect(rows[1].querySelectorAll('td')[3].textContent).toContain('No disponible'); expect(root.textContent).toContain('Página 1 de 1, 2 registros'); http.verify(); }); @@ -106,6 +112,68 @@ describe('Seguimiento TEA', () => { expect(parametros(request())).toEqual(esperados); http.verify(); }); + it('muestra el estado del caso, lo que falta y el módulo junto al puntaje', () => { + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const celdas = fixture.nativeElement.querySelector('tbody tr').querySelectorAll('td'); + expect(celdas[2].textContent).toContain('En proceso'); + expect(celdas[2].textContent).toContain('Falta: Neuropediatría'); + expect(celdas[5].textContent).toContain('8'); + expect(celdas[5].textContent).toContain('Módulo 2'); + http.verify(); + }); + it('resume los EEG arriba de la tabla y filtra por estado y tipo de alteración', () => { + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + expect(Array.from(root.querySelectorAll('.resumen-eeg dd')).map(d => d.textContent)).toEqual(['3', '1', '1', '1', '0']); + expect(root.querySelector('.resumen-eeg')!.textContent).toContain('Picos paroxísticos'); + expect(Array.from(root.querySelector('select[name=alteracion]')!.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Ritmo posterior', 'Picos paroxísticos']); + const c = fixture.componentInstance; + c.draft = { ...c.draft, estado_caso: 'completo', alteracion: 'picos_paroxisticos' }; + c.apply(); + const filtrada = request(); + expect(filtrada.request.params.get('estado_caso')).toBe('completo'); + expect(filtrada.request.params.get('alteracion')).toBe('picos_paroxisticos'); + filtrada.flush(data); fixture.detectChanges(); + expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' }); + http.verify(); + }); + it('al elegir una alteración aparecen sus zonas, con la leyenda, y al repetirla se cierran', () => { + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); + const tarjetas = root.querySelectorAll('button.nombre'); + expect(root.querySelector('section.mapa')).toBeNull(); + expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false); + expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false'); + tarjetas[0].click(); fixture.detectChanges(); + expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true); + expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true'); + const panel = () => root.querySelector('section.mapa')!; + expect(panel().classList.contains('panel')).toBe(false); + expect(panel().textContent).toContain('Azul: menos actividad'); + expect(panel().textContent).toContain('Rojo: más actividad'); + expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior'); + expect(panel().querySelector('.regiones')!.textContent).toContain('Central'); + tarjetas[3].click(); fixture.detectChanges(); + expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos'); + expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital'); + expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false'); + expect(tarjetas[1].disabled).toBe(true); + expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false); + tarjetas[3].click(); fixture.detectChanges(); + expect(root.querySelector('section.mapa')).toBeNull(); + http.verify(); + }); + it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => { + const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo); + const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor; + expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)'); + expect(marco()).toBe('#FFFFFF'); + }); it('sin filtros no envía sus parámetros', () => { open(); expect(request().request.params.keys().sort()).toEqual(['meses', 'page', 'page_size']); @@ -142,7 +210,8 @@ describe('Seguimiento TEA', () => { expect(panel.textContent).toContain('CSS 3'); expect(panel.textContent).toContain('Afecto social (AS)'); expect(panel.textContent).toContain('Aceptable'); - expect(panel.querySelector('app-plotly-chart')).not.toBeNull(); + // The map stays closed until an alteration is chosen. + expect(panel.querySelector('app-plotly-chart')).toBeNull(); // Item scores start collapsed. expect(panel.querySelector('details')!.open).toBe(false); const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!; @@ -198,7 +267,7 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, css: 11 } }, 'T-0001')).toThrow(); const [as, crr] = detalle.ados2.dominios; expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, dominios: [{ ...as, reactivos: [reactivo('A2', 4), as.reactivos[1]] }, crr] } }, 'T-0001')).toThrow(); - expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapa: { ...detalle.eeg.mapa, z: [[0, 0]] } } }, 'T-0001')).toThrow(); + expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow(); expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow(); }); it('la calidad general es una palabra, sus criterios son números y se validan', () => { diff --git a/src/styles.scss b/src/styles.scss index 69fa857..8dfa4e9 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -126,3 +126,15 @@ body { color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; } .indicator-select-panel .option-go:hover { background: var(--issste-accent); } .indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + +// The TEA report: while it's being prepared, charts draw at a width that fits a page. +.dashboard.reporte-impresion .catalog-grid { grid-template-columns: minmax(0, 1fr) !important; max-width: 680px; } +@media print { + .site-header, .site-footer, .institutional-header, .domain-nav, .section-tabs, .global-filters, .catalog-search, .search-result, .reporte-acciones, + .dashboard > header > p, .kpi-grid-oculto, app-indicador-catalog-card button, .catalog-metadata, .selection-status { display: none !important; } + .dashboard app-indicador-catalog-card, .dashboard .resumen { break-inside: avoid; } + .dashboard .plot-viewport { overflow: visible; } + // The app scrolls inside its shell; on paper everything has to flow across pages. + html, body, .app-shell, .app-shell--workspace, .app-main { display: block !important; height: auto !important; min-height: 0 !important; overflow: visible !important; } + body { background: #fff; } +} From a1ea31039e9c6f43663a9fe45a91e312c822f02d Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 13:46:26 -0600 Subject: [PATCH 19/20] feat(tea): abrir las alteraciones del EEG con un mapa visible MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Al desplegar un paciente se abre su primera alteración, o la primera métrica si no tiene alteraciones. Co-Authored-By: Claude Opus 5.5 --- .../indicadores/tea-paciente-resumen.ts | 8 ++++++- .../indicadores/tea-seguimiento.spec.ts | 23 +++++++++++++------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 1170859..2212c2c 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -81,7 +81,13 @@ export class TeaPacienteResumen implements OnInit { load() { this.status.set('loading'); this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ - next: d => { this.mapaElegido = undefined; this.figura = undefined; this.detalle.set(d); this.status.set('ready'); }, + next: d => { + // Opens on the first altered metric, or on the first one if none is altered. + const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0]; + this.mapaElegido = inicial?.codigo; + this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined; + this.detalle.set(d); this.status.set('ready'); + }, error: () => this.status.set('error'), }); } diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 68f907f..5135e4d 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -139,17 +139,13 @@ describe('Seguimiento TEA', () => { expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' }); http.verify(); }); - it('al elegir una alteración aparecen sus zonas, con la leyenda, y al repetirla se cierran', () => { + it('abre con las zonas de la primera alteración, cambia al elegir otra y se cierra al repetirla', () => { const fixture = open(); request().flush(data); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); const tarjetas = root.querySelectorAll('button.nombre'); - expect(root.querySelector('section.mapa')).toBeNull(); - expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false); - expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false'); - tarjetas[0].click(); fixture.detectChanges(); expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true); expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true'); const panel = () => root.querySelector('section.mapa')!; @@ -166,6 +162,9 @@ describe('Seguimiento TEA', () => { expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false); tarjetas[3].click(); fixture.detectChanges(); expect(root.querySelector('section.mapa')).toBeNull(); + expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false); + tarjetas[0].click(); fixture.detectChanges(); + expect(root.querySelector('section.mapa')).not.toBeNull(); http.verify(); }); it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => { @@ -174,6 +173,16 @@ describe('Seguimiento TEA', () => { expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)'); expect(marco()).toBe('#FFFFFF'); }); + it('sin alteraciones abre con la primera métrica evaluable', () => { + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); + const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m); + http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); fixture.detectChanges(); + expect(root.querySelector('section.mapa .meta')!.textContent).toContain('Ritmo posterior'); + http.verify(); + }); it('sin filtros no envía sus parámetros', () => { open(); expect(request().request.params.keys().sort()).toEqual(['meses', 'page', 'page_size']); @@ -210,8 +219,8 @@ describe('Seguimiento TEA', () => { expect(panel.textContent).toContain('CSS 3'); expect(panel.textContent).toContain('Afecto social (AS)'); expect(panel.textContent).toContain('Aceptable'); - // The map stays closed until an alteration is chosen. - expect(panel.querySelector('app-plotly-chart')).toBeNull(); + // Opens with the map of the first altered metric. + expect(panel.querySelector('app-plotly-chart')).not.toBeNull(); // Item scores start collapsed. expect(panel.querySelector('details')!.open).toBe(false); const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!; From 53edec8692b7ee8dca69069333a000513d78d120 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 15:21:18 -0600 Subject: [PATCH 20/20] =?UTF-8?q?feat(tea):=20periodos=20personalizados=20?= =?UTF-8?q?en=20Hist=C3=B3rico?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit «Personalizado…» en «Periodos a mostrar» abre un diálogo con los periodos del intervalo elegido, por año. Las figuras muestran solo los elegidos, sin volver a consultar, y cada intervalo recuerda su propia selección. Co-Authored-By: Claude Opus 5.5 --- .../indicadores-historico-periodos.ts | 58 ++++++++++++++++++ .../indicadores/indicadores-historico.spec.ts | 55 ++++++++++++++++- .../indicadores/indicadores-historico.ts | 61 ++++++++++++++++--- 3 files changed, 161 insertions(+), 13 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-historico-periodos.ts diff --git a/src/app/features/indicadores/indicadores-historico-periodos.ts b/src/app/features/indicadores/indicadores-historico-periodos.ts new file mode 100644 index 0000000..5eeab0e --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-periodos.ts @@ -0,0 +1,58 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { etiquetaPeriodo } from './indicadores-historico-figures'; +import { TipoPeriodo } from './indicadores.models'; + +export interface PeriodosDialogoDatos { tipo: TipoPeriodo; periodos: readonly string[]; elegidos: readonly string[]; } + +// The periods of the chosen analysis interval, by year. Closes with the chosen ones, oldest first, or with nothing if cancelled. +@Component({ + selector: 'app-indicadores-historico-periodos', + imports: [MatButtonModule, MatCheckboxModule, MatDialogModule], + template: ` +

Elegir {{ datos.tipo === 'mes' ? 'meses' : 'semestres' }}

+ +
+ + +
+ @for (grupo of anios; track grupo.anio) { +
+ {{ grupo.anio }} + @for (periodo of grupo.periodos; track periodo) { + {{ etiqueta(periodo) }} + } +
+ } +
+ + {{ cuenta() }} + + + + `, + styles: ` + .acciones { display: flex; gap: .5rem; margin-bottom: .5rem; } + fieldset { display: grid; grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); gap: 0 .5rem; margin: 0 0 .75rem; padding: .25rem .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + legend { padding-inline: .25rem; font-weight: 600; } + .cuenta { margin-inline-end: auto; padding-inline-start: .75rem; font: var(--mat-sys-body-medium); } + `, +}) +export class IndicadoresHistoricoPeriodos { + readonly datos = inject(MAT_DIALOG_DATA); + private readonly dialogo = inject>(MatDialogRef); + readonly etiqueta = etiquetaPeriodo; + readonly todos = [...this.datos.periodos]; + readonly elegidos = signal(this.datos.elegidos); + readonly anios = [...new Set(this.todos.map(p => p.slice(0, 4)))].map(anio => ({ anio, periodos: this.todos.filter(p => p.startsWith(anio)) })); + readonly cuenta = computed(() => { + const n = this.elegidos().length, mes = this.datos.tipo === 'mes'; + return n === 1 ? (mes ? '1 mes elegido' : '1 semestre elegido') : `${n} ${mes ? 'meses elegidos' : 'semestres elegidos'}`; + }); + alternar(periodo: string) { + this.elegidos.update(actual => actual.includes(periodo) ? actual.filter(p => p !== periodo) : [...actual, periodo]); + } + aplicar() { this.dialogo.close(this.todos.filter(p => this.elegidos().includes(p))); } +} diff --git a/src/app/features/indicadores/indicadores-historico.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts index 7c3fb81..2b37c50 100644 --- a/src/app/features/indicadores/indicadores-historico.spec.ts +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -2,7 +2,10 @@ import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog'; +import { Subject } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos'; import { IndicadoresHistorico } from './indicadores-historico'; import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures'; import { Indicador, IndicadorDatos } from './indicadores.models'; @@ -94,6 +97,8 @@ describe('Pestaña Histórico', () => { const datos = (tipo: string, ps: string[]) => ({ id: 'm1', contrato: 'C1', tipo_periodo: tipo, periodos: ps, filas: ps.map(p => c1(p, 50)) }); const datosUrl = '/tea/indicadores/m1/datos'; const render = () => { TestBed.tick(); fixture.detectChanges(); }; + const datos_ = (tipo: string, ps: string[]) => datos(tipo, ps); + const abrir_ = () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush(periodos); http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render(); }; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); @@ -125,7 +130,7 @@ describe('Pestaña Histórico', () => { const semestre = http.expectOne(r => r.url === datosUrl); expect(semestre.request.params.get('periodos')).toBe('2024-S1'); semestre.flush(datos('semestre', ['2024-S1'])); render(); - expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 a 2024 S1 (1 semestre)'); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)'); fixture.componentInstance.tipo.set('mes'); render(); fixture.componentRef.setInput('tema', 'oscuro'); render(); http.expectNone(() => true); @@ -137,7 +142,7 @@ describe('Pestaña Histórico', () => { fixture.componentRef.setInput('active', true); render(); http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] }); http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render(); - expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)']); + expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)', 'Personalizado…']); expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)'); c.elegirVentana(5); render(); expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)'); @@ -145,7 +150,7 @@ describe('Pestaña Histórico', () => { c.tipo.set('semestre'); render(); expect(c.ventana()).toBe(0); http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render(); - expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)']); + expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']); c.tipo.set('mes'); render(); expect(c.ventana()).toBe(5); http.expectNone(() => true); @@ -168,6 +173,31 @@ describe('Pestaña Histórico', () => { expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]); expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3); }); + it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => { + const c = fixture.componentInstance; + const cerrar = new Subject(); + const abrir = vi.spyOn(TestBed.inject(MatDialog), 'open').mockReturnValue({ afterClosed: () => cerrar } as never); + abrir_(); + expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado…'); + c.elegirVentana(-1); + const datos = abrir.mock.calls[0][1]!.data as PeriodosDialogoDatos; + expect(datos).toEqual({ tipo: 'mes', periodos: ['2024-01', '2024-02'], elegidos: ['2024-01', '2024-02'] }); + // Cancelling changes nothing. + cerrar.next(undefined); render(); + expect(c.ventana()).toBe(0); + c.elegirVentana(-1); + cerrar.next(['2024-02']); render(); + expect(c.ventana()).toBe(-1); + expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)'); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)'); + // The other granularity keeps its own choice. + c.tipo.set('semestre'); render(); + expect(c.ventana()).toBe(0); + http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render(); + c.tipo.set('mes'); render(); + expect(c.ventana()).toBe(-1); + http.expectNone(() => true); + }); it('avisa del error sin perder la pestaña y reintenta', () => { abrir(); http.expectOne(r => r.url === datosUrl).flush({}, { status: 500, statusText: 'Error' }); render(); @@ -184,3 +214,22 @@ describe('Pestaña Histórico', () => { expect(fixture.nativeElement.textContent).toContain('Sin reportes publicados'); }); }); + +describe('Diálogo de periodos de Histórico', () => { + it('el diálogo agrupa por año, no aplica sin periodos y devuelve los elegidos en orden', () => { + const cierre = vi.fn(); + TestBed.configureTestingModule({ providers: [{ provide: MAT_DIALOG_DATA, useValue: { tipo: 'mes', periodos: ['2023-12', '2024-01', '2024-02'], elegidos: ['2024-02'] } }, { provide: MatDialogRef, useValue: { close: cierre } }] }); + const dialogo = TestBed.createComponent(IndicadoresHistoricoPeriodos); + dialogo.detectChanges(); + const root: HTMLElement = dialogo.nativeElement; + expect(Array.from(root.querySelectorAll('legend')).map(l => l.textContent)).toEqual(['2023', '2024']); + expect(root.textContent).toContain('dic 2023'); + expect(root.querySelector('.cuenta')!.textContent).toBe('1 mes elegido'); + const aplicar = Array.from(root.querySelectorAll('button')).find(b => b.textContent?.trim() === 'Aplicar')!; + dialogo.componentInstance.elegidos.set([]); dialogo.detectChanges(); + expect(aplicar.disabled).toBe(true); + dialogo.componentInstance.alternar('2024-01'); dialogo.componentInstance.alternar('2023-12'); dialogo.detectChanges(); + aplicar.click(); + expect(cierre).toHaveBeenCalledWith(['2023-12', '2024-01']); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index b982981..4128aa9 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -1,14 +1,16 @@ -import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatDialog } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatSelectModule } from '@angular/material/select'; +import { MatSelect, MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; import { httpMessage } from './indicadores-http'; +import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos'; import { IndicadoresPeriodos } from './indicadores-periodos'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; @@ -19,6 +21,7 @@ type Panel = { item: Pick; rango?: stri { estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; const CASOS = 'M28_casos_por_estado'; +const PERSONALIZADO = -1; // The screening steps go together as small charts, and the case counts are followed by their in-process share. function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] { @@ -54,10 +57,11 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P Periodos a mostrar - + @for (opcion of opciones(); track opcion.valor) { {{ opcion.etiqueta }} } + @if (ventana() === PERSONALIZADO) { }
@for (panel of paneles(); track panel.item.id) { @@ -111,7 +115,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 { min-width: 14rem; } + mat-form-field { min-width: 18rem; } `, }) export class IndicadoresHistorico { @@ -123,6 +127,21 @@ export class IndicadoresHistorico { // How many of the latest periods to show, per granularity; 0 shows them all. private readonly ventanas = signal>>({}); readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0); + readonly PERSONALIZADO = PERSONALIZADO; + // The periods the user picked in the dialog, per granularity. + private readonly personalizados = signal>>({}); + private readonly dialogo = inject(MatDialog); + private readonly selector = viewChild('selector'); + // Every period published for the granularity by any indicator. + private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {}) + .flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : []))); + // The periods on screen, out of those an indicator publishes. + private recortar(periodos: readonly string[]) { + const orden = cronologico(periodos), ventana = this.ventana(); + if (ventana !== PERSONALIZADO) return orden.slice(-ventana); + const elegidos = this.personalizados()[this.tipo()] ?? []; + return orden.filter(p => elegidos.includes(p)); + } private readonly service = inject(IndicadoresService); private readonly periodos = inject(IndicadoresPeriodos); private readonly cargas = signal>>>({}); @@ -136,24 +155,28 @@ export class IndicadoresHistorico { const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0)); const opciones = []; for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` }); - return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' }]; + const elegidos = this.personalizados()[tipo]?.length; + return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' }, + ...(total ? [{ valor: PERSONALIZADO, etiqueta: elegidos && this.ventana() === PERSONALIZADO ? `Personalizado (${elegidos} ${unidad(tipo, elegidos)})` : 'Personalizado…' }] : [])]; }); readonly paneles = computed(() => { - const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(), ventana = this.ventana(); + const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(); // Top of the shared scale: the highest third quartile of the steps, in the periods on screen. const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => { const carga = cargas?.[id]; if (carga?.estado !== 'listo') return []; - const visibles = cronologico(carga.datos.periodos).slice(-ventana); + const visibles = this.recortar(carga.datos.periodos); return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0); })) * 1.05; const base: (Panel & { datos?: IndicadorDatos })[] = this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(item => { const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; if (carga.estado !== 'listo') return { item, ...carga }; - const periodos = cronologico(carga.datos.periodos).slice(-ventana); + const periodos = this.recortar(carga.datos.periodos); + if (!periodos.length) return { item, estado: 'vacio' }; const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) }; - const rango = `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])} (${periodos.length} ${unidad(tipo, periodos.length)})`; + const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`; + const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`; try { return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos }; } catch (error) { @@ -188,7 +211,25 @@ export class IndicadoresHistorico { : of({ estado: 'vacio' })), catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); } - elegirVentana(valor: number) { this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); } + elegirVentana(valor: number) { + if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; } + this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); + } + abrirPersonalizado() { + const tipo = this.tipo(), periodos = this.disponibles(); + // Starts from what's on screen, so the user only adjusts it. + const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : periodos.slice(-this.ventana()); + const data: PeriodosDialogoDatos = { tipo, periodos, elegidos }; + this.dialogo.open(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' }) + .afterClosed().subscribe(resultado => { + if (resultado?.length) { + this.personalizados.update(actual => ({ ...actual, [tipo]: resultado })); + this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO })); + } + // Cancelled, the selector goes back to what's on screen. + this.selector()?.writeValue(this.ventana()); + }); + } reintentar() { const tipo = this.tipo(); this.solicitada = tipo;