From 2cbb9946677d9de7ec65d3efe6af2729dc5492d3 Mon Sep 17 00:00:00 2001 From: edgar Date: Thu, 29 Oct 2026 02:38:43 +0000 Subject: [PATCH 01/27] 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/27] 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/27] =?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; From e8628508d8d31fc38a4852c25d9fe46e00f7dea8 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 00:33:01 -0600 Subject: [PATCH 21/27] KPIs page drawing CaCu's measures from the WebApi's FHIR MeasureReport bundles --- src/app/app.routes.ts | 6 + .../cacu_eu13_measure_report_bundle.json | 127 ++++++++ .../cacu_eu7_measure_report_bundle.json | 295 ++++++++++++++++++ .../cacu_ind1_measure_report_bundle.json | 155 +++++++++ .../indicadores/indicador-measure-report.ts | 35 +++ src/app/features/indicadores/kpis-page.ts | 39 +++ .../indicadores/measure-report.service.ts | 34 ++ .../indicadores/measure-report.spec.ts | 145 +++++++++ .../features/indicadores/measure-report.ts | 147 +++++++++ 9 files changed, 983 insertions(+) create mode 100644 src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json create mode 100644 src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json create mode 100644 src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json create mode 100644 src/app/features/indicadores/indicador-measure-report.ts create mode 100644 src/app/features/indicadores/kpis-page.ts create mode 100644 src/app/features/indicadores/measure-report.service.ts create mode 100644 src/app/features/indicadores/measure-report.spec.ts create mode 100644 src/app/features/indicadores/measure-report.ts diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 66070ed..2249119 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -26,6 +26,12 @@ export const routes: Routes = [ loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage), data: { workspace: true, breadcrumb: 'Bitácora de cargas' }, }, + { + path: 'kpis', + title: 'Indicadores | ISSSTELEON', + loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage), + data: { workspace: true, breadcrumb: 'Indicadores' }, + }, { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, ...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, diff --git a/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json new file mode 100644 index 0000000..d23a6f2 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json @@ -0,0 +1,127 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 1, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_EU13|0.3.2", + "date": "2026-11-08T00:28:51.413089+00:00", + "period": { + "start": "2025-01-01", + "end": "2025-06-30" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:51.351883+00:00" + } + ], + "group": [ + { + "id": "principal", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 0 + } + ], + "measureScore": { + "value": 0.0 + }, + "stratifier": [ + { + "code": [ + { + "text": "grupo_edad" + } + ], + "stratum": [ + { + "value": { + "text": "45-54" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 0 + } + ], + "measureScore": { + "value": 0.0 + } + } + ] + } + ] + } + ] + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json new file mode 100644 index 0000000..36b91a3 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json @@ -0,0 +1,295 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 2, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_EU7|0.3.3", + "date": "2026-11-08T00:28:56.089006+00:00", + "period": { + "start": "2025-01-01", + "end": "2025-06-30" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:56.025101+00:00" + } + ], + "group": [ + { + "id": "TOTAL", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "count": 4 + } + ], + "stratifier": [ + { + "code": [ + { + "text": "resultado" + } + ], + "stratum": [ + { + "value": { + "text": "LIEBG" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + }, + { + "value": { + "text": "NEGATIVO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 2 + } + ] + }, + { + "value": { + "text": "SIN_DATO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + } + ] + }, + { + "code": [ + { + "text": "grupo_edad" + } + ], + "stratum": [ + { + "value": { + "text": "45-54" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + } + ] + } + ] + } + ] + } + ] + } + }, + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_EU7|0.3.3", + "date": "2026-11-08T00:28:56.099338+00:00", + "period": { + "start": "2025-07-01", + "end": "2025-12-31" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 2 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:56.025101+00:00" + } + ], + "group": [ + { + "id": "TOTAL", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "count": 4 + } + ], + "stratifier": [ + { + "code": [ + { + "text": "resultado" + } + ], + "stratum": [ + { + "value": { + "text": "LIEAG" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + }, + { + "value": { + "text": "NEGATIVO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 1 + } + ] + }, + { + "value": { + "text": "SIN_DATO" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 2 + } + ] + } + ] + }, + { + "code": [ + { + "text": "grupo_edad" + } + ], + "stratum": [ + { + "value": { + "text": "45-54" + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + } + ] + } + ] + } + ] + } + ] + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json new file mode 100644 index 0000000..4615f5c --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json @@ -0,0 +1,155 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 2, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/IND1|0.3.2", + "date": "2026-11-08T00:28:50.038223+00:00", + "period": { + "start": "2025-01-01", + "end": "2025-06-30" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:49.977023+00:00" + } + ], + "group": [ + { + "id": "principal", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 1 + } + ], + "measureScore": { + "value": 0.25 + } + } + ], + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + } + } + }, + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/IND1|0.3.2", + "date": "2026-11-08T00:28:50.044435+00:00", + "period": { + "start": "2025-07-01", + "end": "2025-12-31" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 2 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T00:28:49.977023+00:00" + } + ], + "group": [ + { + "id": "principal", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "denominator" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "numerator" + } + ] + }, + "count": 1 + } + ], + "measureScore": { + "value": 0.25 + } + } + ], + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/indicador-measure-report.ts b/src/app/features/indicadores/indicador-measure-report.ts new file mode 100644 index 0000000..c371f96 --- /dev/null +++ b/src/app/features/indicadores/indicador-measure-report.ts @@ -0,0 +1,35 @@ +import { Component, inject, Input, OnChanges, signal } from '@angular/core'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, PlotlyFigure } from './indicadores.models'; +import { proportionFigure } from './measure-report'; +import { MeasureReportService } from './measure-report.service'; + +/** A proportion drawn from the WebApi's FHIR `MeasureReport`s: the data comes as the standard, the figure is ours. */ +@Component({ + selector: 'app-indicador-measure-report', + imports: [MatProgressBarModule, PlotlyChart], + template: ` + @if (status() === 'loading') { } + @if (status() === 'error') {

No se pudo cargar el indicador.

} + @if (figure(); as figure) { } + `, +}) +export class IndicadorMeasureReport implements OnChanges { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: string; + @Input({ required: true }) titulo!: string; + @Input({ required: true }) periodos!: string[]; + @Input() estrato?: string; + readonly status = signal<'loading' | 'ready' | 'error'>('loading'); + readonly figure = signal(undefined); + private readonly service = inject(MeasureReportService); + + ngOnChanges() { + this.status.set('loading'); + this.service.series(this.dominio, this.indicador, this.periodos).subscribe({ + next: series => { this.figure.set(proportionFigure(series, this.titulo, this.estrato)); this.status.set('ready'); }, + error: () => { this.figure.set(undefined); this.status.set('error'); }, + }); + } +} diff --git a/src/app/features/indicadores/kpis-page.ts b/src/app/features/indicadores/kpis-page.ts new file mode 100644 index 0000000..8530413 --- /dev/null +++ b/src/app/features/indicadores/kpis-page.ts @@ -0,0 +1,39 @@ +import { Component, inject, OnInit, signal } from '@angular/core'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { forkJoin, map, of, switchMap } from 'rxjs'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from './indicadores.models'; +import { compositionFigure, proportionFigure } from './measure-report'; +import { MeasureReportService } from './measure-report.service'; + +const PERIODOS = ['2025-S1', '2025-S2']; + +/** Every measure the WebApi answers on request, drawn from its FHIR `MeasureReport`s: one contract for all. */ +@Component({ + selector: 'app-kpis-page', + imports: [MatProgressBarModule, PlotlyChart], + template: ` +

Indicadores

+ @if (status() === 'loading') { } + @if (status() === 'error') {

No se pudieron cargar los indicadores.

} + @for (item of figures(); track item.id) { +
+ } + `, +}) +export class KpisPage implements OnInit { + readonly status = signal<'loading' | 'ready' | 'error'>('loading'); + readonly figures = signal<{ id: string; figure: PlotlyFigure }[]>([]); + private readonly service = inject(MeasureReportService); + + ngOnInit() { + this.service.list('cacu').pipe( + switchMap(kpis => kpis.length === 0 ? of([]) : forkJoin(kpis.map(kpi => kpi.scoring === 'composition' + ? this.service.composition('cacu', kpi.id, PERIODOS).pipe(map(s => ({ id: kpi.id, figure: compositionFigure(s, kpi.id) }))) + : this.service.series('cacu', kpi.id, PERIODOS).pipe(map(s => ({ id: kpi.id, figure: proportionFigure(s, kpi.id) })))))), + ).subscribe({ + next: figures => { this.figures.set(figures); this.status.set('ready'); }, + error: () => this.status.set('error'), + }); + } +} diff --git a/src/app/features/indicadores/measure-report.service.ts b/src/app/features/indicadores/measure-report.service.ts new file mode 100644 index 0000000..b290516 --- /dev/null +++ b/src/app/features/indicadores/measure-report.service.ts @@ -0,0 +1,34 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { Dominio, requireDominio } from './indicadores.models'; +import { CompositionSeries, compositionFrom, MeasureReportBundle, Series, seriesFrom } from './measure-report'; + +export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' } + +/** A measure's periods answered on request by the WebApi, as FHIR `MeasureReport`s, read into a series. */ +@Injectable({ providedIn: 'root' }) +export class MeasureReportService { + private readonly http = inject(HttpClient); + + /** The measures the WebApi answers on request for the domain. */ + list(dominio: Dominio) { + return this.http.get(`/${requireDominio(dominio)}/kpis`); + } + + composition(dominio: Dominio, indicador: string, periodos: string[]) { + const params = new HttpParams().set('periodos', periodos.join(',')); + return this.http + .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .pipe(map((bundle): CompositionSeries => compositionFrom(bundle))); + } + + series(dominio: Dominio, indicador: string, periodos: string[], cortes: { evento?: string; conocimiento?: string } = {}) { + let params = new HttpParams().set('periodos', periodos.join(',')); + if (cortes.evento) params = params.set('corte_evento', cortes.evento); + if (cortes.conocimiento) params = params.set('corte_conocimiento', cortes.conocimiento); + return this.http + .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .pipe(map((bundle): Series => seriesFrom(bundle))); + } +} diff --git a/src/app/features/indicadores/measure-report.spec.ts b/src/app/features/indicadores/measure-report.spec.ts new file mode 100644 index 0000000..98d8783 --- /dev/null +++ b/src/app/features/indicadores/measure-report.spec.ts @@ -0,0 +1,145 @@ +// What this covers: reading the WebApi's FHIR `MeasureReport` bundles (`//kpis/`) into a series, drawing +// it here, the service that asks for it and the component that shows it. +// Fixtures: `cacu_ind1_measure_report_bundle.json` (IND1, 2025-S1 and 2025-S2) and +// `cacu_eu13_measure_report_bundle.json` (EU13, 2025-S1, with the `grupo_edad` stratifier) and +// `cacu_eu7_measure_report_bundle.json` (EU7, a composition, 2025-S1 and 2025-S2): written by the WebApi's +// route tests over the synthetic fixture database, counts only. +import { Component, input } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { firstValueFrom } from 'rxjs'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import ind1 from './fixtures/cacu_ind1_measure_report_bundle.json'; +import eu13 from './fixtures/cacu_eu13_measure_report_bundle.json'; +import eu7 from './fixtures/cacu_eu7_measure_report_bundle.json'; +import { IndicadorMeasureReport } from './indicador-measure-report'; +import { compositionFigure, compositionFrom, InvalidMeasureReport, MeasureReportBundle, periodLabel, proportionFigure, seriesFrom } from './measure-report'; +import { KpisPage } from './kpis-page'; +import { MeasureReportService } from './measure-report.service'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { figure = input(); label = input(); } + +const IND1 = ind1 as unknown as MeasureReportBundle; +const EU13 = eu13 as unknown as MeasureReportBundle; +const EU7 = eu7 as unknown as MeasureReportBundle; + +describe('measure reports', () => { + it('names a period from its FHIR dates', () => { + // Pins down: semesters and months read as the WebApp names them. Fails if FHIR's inclusive end is misread. + expect(periodLabel({ start: '2025-01-01', end: '2025-06-30' })).toBe('2025-S1'); + expect(periodLabel({ start: '2025-07-01', end: '2025-12-31' })).toBe('2025-S2'); + expect(periodLabel({ start: '2025-03-01', end: '2025-03-31' })).toBe('2025-03'); + expect(periodLabel({ start: '2025-01-01', end: '2025-03-31' })).toBe('2025-01-01 a 2025-03-31'); + }); + + it('reads one point per period from a bundle', () => { + // Pins down: the counts come from the populations, the order from the bundle. Fails if the reading of FHIR's + // population codes or of `improvementNotation` changes. + const series = seriesFrom(IND1); + expect(series.measure).toBe('cacu/IND1|0.3.2'); + expect(series.lowerIsBetter).toBe(true); + expect(series.total).toEqual([ + { period: '2025-S1', numerator: 1, denominator: 4, value: 0.25 }, + { period: '2025-S2', numerator: 1, denominator: 4, value: 0.25 }, + ]); + }); + + it('reads the strata of a stratifier', () => { + // Pins down: each stratum's value is a series of its own. Fails if `stratifier` stops being read. + expect(seriesFrom(EU13).strata).toEqual({ + grupo_edad: { '45-54': [{ period: '2025-S1', numerator: 0, denominator: 4, value: 0 }] }, + }); + }); + + it('rejects what is not a bundle of reports of one measure', () => { + // Pins down: a malformed answer fails loudly instead of drawing zeros. Fails if validation is dropped. + expect(() => seriesFrom({ resourceType: 'Bundle', entry: [] } as MeasureReportBundle)).toThrow(InvalidMeasureReport); + const mixed = { ...IND1, entry: [IND1.entry[0], { resource: { ...IND1.entry[1].resource, measure: 'otro' } }] }; + expect(() => seriesFrom(mixed)).toThrow(InvalidMeasureReport); + }); + + it('draws the figure here: percentages per period, one line per stratum value', () => { + // Pins down: the WebApp decides the figure from the data. Fails if values stop being percentages, or a + // stratum stops giving one trace per value. + const total = proportionFigure(seriesFrom(IND1), 'Pacientes con citología anómala'); + expect(total.data).toHaveLength(1); + expect(total.data[0]['x']).toEqual(['2025-S1', '2025-S2']); + expect(total.data[0]['y']).toEqual([25, 25]); + const byAge = proportionFigure(seriesFrom(EU13), 'Tasa de detección', 'grupo_edad'); + expect(byAge.data.map(trace => trace['name'])).toEqual(['45-54']); + }); +}); + +describe('MeasureReportService and IndicadorMeasureReport', () => { + beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); + + it('asks the WebApi for the periods and cut-offs and reads the bundle', async () => { + // Pins down the request: the route, `periodos` comma-separated and the cut-offs only when given. Fails if + // the URL or a parameter's name drifts from the WebApi's. + const answer = firstValueFrom(TestBed.inject(MeasureReportService) + .series('cacu', 'IND1', ['2025-S1', '2025-S2'], { evento: '2025-12-31' })); + const request = TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/kpis/IND1'); + expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); + expect(request.request.params.get('corte_evento')).toBe('2025-12-31'); + expect(request.request.params.has('corte_conocimiento')).toBe(false); + request.flush(IND1); + expect((await answer).total.map(p => p.value)).toEqual([0.25, 0.25]); + }); + + it('shows the figure it drew from the answer', () => { + // Pins down: the component hands the chart the figure built from the bundle. Fails if it stops drawing. + TestBed.overrideComponent(IndicadorMeasureReport, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + const fixture = TestBed.createComponent(IndicadorMeasureReport); + Object.assign(fixture.componentInstance, { dominio: 'cacu', indicador: 'IND1', titulo: 'IND1', periodos: ['2025-S1', '2025-S2'] }); + fixture.componentInstance.ngOnChanges(); + TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/kpis/IND1').flush(IND1); + fixture.detectChanges(); + expect(fixture.componentInstance.status()).toBe('ready'); + expect(fixture.componentInstance.figure()?.data[0]['y']).toEqual([25, 25]); + }); +}); + +describe('compositions', () => { + it('reads the categories of each period from the `resultado` stratifier', () => { + // Pins down: a composition is a count per category and period, zero where a period lacks one. Fails if the + // stratifier stops being read or a missing category stops being zero. + const series = compositionFrom(EU7); + expect(series.periods).toEqual(['2025-S1', '2025-S2']); + expect(series.categories).toEqual({ LIEBG: [1, 0], NEGATIVO: [2, 1], SIN_DATO: [1, 2], LIEAG: [0, 1] }); + }); + + it('draws stacked bars, one segment per category', () => { + // Pins down: the WebApp draws compositions from the same contract. Fails if a category stops being a trace. + const figure = compositionFigure(compositionFrom(EU7), 'EU7'); + expect(figure.layout['barmode']).toBe('stack'); + expect(figure.data.map(trace => trace['name']).sort()).toEqual(['LIEAG', 'LIEBG', 'NEGATIVO', 'SIN_DATO']); + }); +}); + +describe('KpisPage', () => { + beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); + + it('draws every measure the WebApi lists, each from its reports', () => { + // Pins down: the page needs nothing per measure: it lists `/cacu/kpis` and draws proportions and compositions + // from the one contract. Fails if a scoring stops being drawn or the page starts naming measures. + TestBed.overrideComponent(KpisPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + const fixture = TestBed.createComponent(KpisPage); + fixture.componentInstance.ngOnInit(); + const http = TestBed.inject(HttpTestingController); + http.expectOne('/cacu/kpis').flush([ + { id: 'IND1', url: 'cacu/IND1', version: '0.3.2', scoring: 'proportion' }, + { id: 'CACU_EU13', url: 'cacu/CACU_EU13', version: '0.3.2', scoring: 'proportion' }, + { id: 'CACU_EU7', url: 'cacu/CACU_EU7', version: '0.3.3', scoring: 'composition' }, + ]); + http.expectOne(r => r.url === '/cacu/kpis/IND1').flush(IND1); + http.expectOne(r => r.url === '/cacu/kpis/CACU_EU13').flush(EU13); + http.expectOne(r => r.url === '/cacu/kpis/CACU_EU7').flush(EU7); + fixture.detectChanges(); + expect(fixture.componentInstance.status()).toBe('ready'); + expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7']); + expect(fixture.componentInstance.figures()[2].figure.layout['barmode']).toBe('stack'); + }); +}); + diff --git a/src/app/features/indicadores/measure-report.ts b/src/app/features/indicadores/measure-report.ts new file mode 100644 index 0000000..953b8f6 --- /dev/null +++ b/src/app/features/indicadores/measure-report.ts @@ -0,0 +1,147 @@ +import { PlotlyFigure } from './indicadores.models'; + +/** The part of FHIR R4's `MeasureReport` the WebApi's `//kpis/` serves: one group, its populations, + * its score and its strata. */ +export interface CodeableConcept { coding?: { system?: string; code: string }[]; text?: string } +export interface ReportPopulation { code: CodeableConcept; count: number } +export interface ReportStratum { value: CodeableConcept; population: ReportPopulation[]; measureScore?: { value: number } } +export interface ReportStratifier { code: CodeableConcept[]; stratum: ReportStratum[] } +export interface ReportGroup { + id?: string; + population: ReportPopulation[]; + measureScore?: { value: number }; + stratifier?: ReportStratifier[]; +} +export interface MeasureReport { + resourceType: 'MeasureReport'; + status: string; + type: string; + measure: string; + period: { start: string; end: string }; + group: ReportGroup[]; + improvementNotation?: CodeableConcept; + extension?: { url: string; valueDate?: string; valueDateTime?: string; valueInteger?: number }[]; +} +export interface MeasureReportBundle { resourceType: 'Bundle'; entry: { resource: MeasureReport }[] } + +/** One period of a series: its label, the counts and the proportion (null without a denominator). */ +export interface Point { period: string; numerator: number; denominator: number; value: number | null } +export interface Series { + measure: string; + lowerIsBetter: boolean; + total: Point[]; + strata: Record>; +} + +export class InvalidMeasureReport extends Error {} + +/** "2025-S1", "2025-03" or "2025-01-01 a 2025-03-31": the period's name from FHIR's dates (the end is inclusive). */ +export function periodLabel(period: { start: string; end: string }): string { + const [y1, m1, d1] = period.start.split('-').map(Number); + const [y2, m2] = period.end.split('-').map(Number); + const months = (y2 - y1) * 12 + (m2 - m1) + 1; + if (d1 === 1 && months === 1) return `${y1}-${String(m1).padStart(2, '0')}`; + if (d1 === 1 && months === 6 && (m1 === 1 || m1 === 7)) return `${y1}-S${m1 === 1 ? 1 : 2}`; + return `${period.start} a ${period.end}`; +} + +function count(populations: ReportPopulation[], code: string): number { + const found = populations.find(p => p.code.coding?.some(c => c.code === code)); + if (!found || !Number.isInteger(found.count) || found.count < 0) throw new InvalidMeasureReport(`Falta la población ${code}`); + return found.count; +} + +function point(period: string, populations: ReportPopulation[]): Point { + const numerator = count(populations, 'numerator'); + const denominator = count(populations, 'denominator'); + return { period, numerator, denominator, value: denominator ? numerator / denominator : null }; +} + +/** The series of a measure from the reports of its periods, in the order they came. */ +export function seriesFrom(bundle: MeasureReportBundle): Series { + if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) { + throw new InvalidMeasureReport('Respuesta de KPI inválida'); + } + const reports = bundle.entry.map(e => e.resource); + if (!reports.every(r => r?.resourceType === 'MeasureReport' && r.group?.length === 1)) { + throw new InvalidMeasureReport('Respuesta de KPI inválida'); + } + const measures = new Set(reports.map(r => r.measure)); + if (measures.size !== 1) throw new InvalidMeasureReport('Los reportes son de indicadores distintos'); + const strata: Series['strata'] = {}; + const total = reports.map(report => { + const period = periodLabel(report.period); + const [group] = report.group; + for (const stratifier of group.stratifier ?? []) { + const name = stratifier.code[0]?.text ?? ''; + for (const stratum of stratifier.stratum) { + const value = stratum.value.text ?? ''; + ((strata[name] ??= {})[value] ??= []).push(point(period, stratum.population)); + } + } + return point(period, group.population); + }); + const lowerIsBetter = reports[0].improvementNotation?.coding?.some(c => c.code === 'decrease') ?? false; + return { measure: reports[0].measure, lowerIsBetter, total, strata }; +} + +const hover = (p: Point) => `${p.period}
${p.numerator} de ${p.denominator}` + + (p.value === null ? '
sin denominador' : `
${(100 * p.value).toFixed(1)} %`); + +/** The figure, drawn here: one point per period, as a percentage; with a stratum, one line per value. */ +export function proportionFigure(series: Series, title: string, stratum?: string): PlotlyFigure { + const traces = stratum + ? Object.entries(series.strata[stratum] ?? {}).map(([value, points]) => ({ name: value, points })) + : [{ name: 'Total', points: series.total }]; + const data = traces.map(({ name, points }) => ({ + type: 'scatter', mode: 'lines+markers', name, + x: points.map(p => p.period), + y: points.map(p => (p.value === null ? null : 100 * p.value)), + text: points.map(hover), hoverinfo: 'text', + })); + const notes = series.lowerIsBetter ? [{ text: 'Menos es mejor.', showarrow: false, xref: 'paper', yref: 'paper', x: 0, y: -0.2 }] : []; + return { + data, + layout: { + title: { text: title }, showlegend: traces.length > 1, + xaxis: { type: 'category', title: { text: 'Periodo' } }, + yaxis: { title: { text: 'Porcentaje' }, ticksuffix: ' %', rangemode: 'tozero' }, + annotations: notes, + }, + }; +} + + +/** A composition: per period, how many units fall in each category of its `resultado` stratifier. */ +export interface CompositionSeries { measure: string; periods: string[]; categories: Record } + +export function compositionFrom(bundle: MeasureReportBundle, stratifier = 'resultado'): CompositionSeries { + if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) { + throw new InvalidMeasureReport('Respuesta de KPI inválida'); + } + const reports = bundle.entry.map(e => e.resource); + const periods = reports.map(r => periodLabel(r.period)); + const categories: Record = {}; + reports.forEach((report, i) => { + const found = report.group[0]?.stratifier?.find(s => s.code[0]?.text === stratifier); + if (!found) throw new InvalidMeasureReport(`Falta el estratificador ${stratifier}`); + for (const stratum of found.stratum) { + const name = stratum.value.text ?? ''; + (categories[name] ??= periods.map(() => 0))[i] = count(stratum.population, 'initial-population'); + } + }); + return { measure: reports[0].measure, periods, categories }; +} + +/** Stacked bars, one per period, a segment per category, drawn here. */ +export function compositionFigure(series: CompositionSeries, title: string): PlotlyFigure { + const data = Object.entries(series.categories).map(([name, counts]) => ({ + type: 'bar', name, x: series.periods, y: counts, + text: counts.map((n, i) => `${series.periods[i]}
${name}: ${n}`), hoverinfo: 'text', + })); + return { + data, + layout: { title: { text: title }, barmode: 'stack', showlegend: true, + xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' } }, + }; +} From 8f2906fe6f73ad6747303a53202e1403b4f3bf8b Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 01:16:04 -0600 Subject: [PATCH 22/27] KPIs page draws durations as boxes and reads a composition's categories from its first stratifier --- ...oma_diagnostico_measure_report_bundle.json | 85 +++++++++++++++++++ src/app/features/indicadores/kpis-page.ts | 21 +++-- .../indicadores/measure-report.service.ts | 11 ++- .../indicadores/measure-report.spec.ts | 54 ++++++++++-- .../features/indicadores/measure-report.ts | 55 ++++++++++-- 5 files changed, 208 insertions(+), 18 deletions(-) create mode 100644 src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json diff --git a/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json new file mode 100644 index 0000000..d337f2a --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json @@ -0,0 +1,85 @@ +{ + "resourceType": "Bundle", + "type": "searchset", + "total": 1, + "entry": [ + { + "resource": { + "resourceType": "MeasureReport", + "status": "complete", + "type": "summary", + "measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3", + "date": "2026-11-08T06:47:32.900609+00:00", + "period": { + "start": "2025-07-01", + "end": "2025-12-31" + }, + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id", + "valueInteger": 1 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento", + "valueDate": "2026-11-08" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento", + "valueDateTime": "2026-11-08T06:47:32.766239+00:00" + } + ], + "group": [ + { + "id": "TOTAL", + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "count": 4 + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "count": 2 + } + ], + "measureScore": { + "value": 100.5, + "unit": "d", + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/q1", + "valueDecimal": 70.25 + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/q3", + "valueDecimal": 130.75 + } + ] + } + } + ], + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/kpis-page.ts b/src/app/features/indicadores/kpis-page.ts index 8530413..d665db8 100644 --- a/src/app/features/indicadores/kpis-page.ts +++ b/src/app/features/indicadores/kpis-page.ts @@ -3,8 +3,8 @@ import { MatProgressBarModule } from '@angular/material/progress-bar'; import { forkJoin, map, of, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; -import { compositionFigure, proportionFigure } from './measure-report'; -import { MeasureReportService } from './measure-report.service'; +import { compositionFigure, durationFigure, proportionFigure } from './measure-report'; +import { KpiEntry, MeasureReportService } from './measure-report.service'; const PERIODOS = ['2025-S1', '2025-S2']; @@ -28,12 +28,23 @@ export class KpisPage implements OnInit { ngOnInit() { this.service.list('cacu').pipe( - switchMap(kpis => kpis.length === 0 ? of([]) : forkJoin(kpis.map(kpi => kpi.scoring === 'composition' - ? this.service.composition('cacu', kpi.id, PERIODOS).pipe(map(s => ({ id: kpi.id, figure: compositionFigure(s, kpi.id) }))) - : this.service.series('cacu', kpi.id, PERIODOS).pipe(map(s => ({ id: kpi.id, figure: proportionFigure(s, kpi.id) })))))), + switchMap(kpis => kpis.length === 0 ? of([]) : forkJoin(kpis.map(kpi => this.figureOf(kpi)))), ).subscribe({ next: figures => { this.figures.set(figures); this.status.set('ready'); }, error: () => this.status.set('error'), }); } + + /** Drawn by its scoring, from the one contract: nothing here is per measure. */ + private figureOf(kpi: KpiEntry) { + const drawn = (figure: PlotlyFigure) => ({ id: kpi.id, figure }); + switch (kpi.scoring) { + case 'composition': + return this.service.composition('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(compositionFigure(s, kpi.id)))); + case 'continuous-variable': + return this.service.duration('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(durationFigure(s, kpi.id)))); + default: + return this.service.series('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(proportionFigure(s, kpi.id)))); + } + } } diff --git a/src/app/features/indicadores/measure-report.service.ts b/src/app/features/indicadores/measure-report.service.ts index b290516..a26dd5d 100644 --- a/src/app/features/indicadores/measure-report.service.ts +++ b/src/app/features/indicadores/measure-report.service.ts @@ -2,9 +2,9 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { Dominio, requireDominio } from './indicadores.models'; -import { CompositionSeries, compositionFrom, MeasureReportBundle, Series, seriesFrom } from './measure-report'; +import { CompositionSeries, compositionFrom, DurationSeries, durationFrom, MeasureReportBundle, Series, seriesFrom } from './measure-report'; -export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' } +export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' | 'continuous-variable' } /** A measure's periods answered on request by the WebApi, as FHIR `MeasureReport`s, read into a series. */ @Injectable({ providedIn: 'root' }) @@ -23,6 +23,13 @@ export class MeasureReportService { .pipe(map((bundle): CompositionSeries => compositionFrom(bundle))); } + duration(dominio: Dominio, indicador: string, periodos: string[]) { + const params = new HttpParams().set('periodos', periodos.join(',')); + return this.http + .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .pipe(map((bundle): DurationSeries => durationFrom(bundle))); + } + series(dominio: Dominio, indicador: string, periodos: string[], cortes: { evento?: string; conocimiento?: string } = {}) { let params = new HttpParams().set('periodos', periodos.join(',')); if (cortes.evento) params = params.set('corte_evento', cortes.evento); diff --git a/src/app/features/indicadores/measure-report.spec.ts b/src/app/features/indicadores/measure-report.spec.ts index 98d8783..efa9ae1 100644 --- a/src/app/features/indicadores/measure-report.spec.ts +++ b/src/app/features/indicadores/measure-report.spec.ts @@ -2,8 +2,9 @@ // it here, the service that asks for it and the component that shows it. // Fixtures: `cacu_ind1_measure_report_bundle.json` (IND1, 2025-S1 and 2025-S2) and // `cacu_eu13_measure_report_bundle.json` (EU13, 2025-S1, with the `grupo_edad` stratifier) and -// `cacu_eu7_measure_report_bundle.json` (EU7, a composition, 2025-S1 and 2025-S2): written by the WebApi's -// route tests over the synthetic fixture database, counts only. +// `cacu_eu7_measure_report_bundle.json` (EU7, a composition, 2025-S1 and 2025-S2) and +// `cacu_dias_toma_diagnostico_measure_report_bundle.json` (days to diagnosis, a duration, 2025-S2): written by the +// WebApi's route tests over the synthetic fixture database, counts and days only. import { Component, input } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -13,8 +14,9 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import ind1 from './fixtures/cacu_ind1_measure_report_bundle.json'; import eu13 from './fixtures/cacu_eu13_measure_report_bundle.json'; import eu7 from './fixtures/cacu_eu7_measure_report_bundle.json'; +import dias from './fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json'; import { IndicadorMeasureReport } from './indicador-measure-report'; -import { compositionFigure, compositionFrom, InvalidMeasureReport, MeasureReportBundle, periodLabel, proportionFigure, seriesFrom } from './measure-report'; +import { compositionFigure, compositionFrom, durationFigure, durationFrom, InvalidMeasureReport, MeasureReportBundle, periodLabel, proportionFigure, seriesFrom } from './measure-report'; import { KpisPage } from './kpis-page'; import { MeasureReportService } from './measure-report.service'; @@ -24,6 +26,7 @@ class ChartStub { figure = input(); label = input(); } const IND1 = ind1 as unknown as MeasureReportBundle; const EU13 = eu13 as unknown as MeasureReportBundle; const EU7 = eu7 as unknown as MeasureReportBundle; +const DIAS = dias as unknown as MeasureReportBundle; describe('measure reports', () => { it('names a period from its FHIR dates', () => { @@ -110,6 +113,15 @@ describe('compositions', () => { expect(series.categories).toEqual({ LIEBG: [1, 0], NEGATIVO: [2, 1], SIN_DATO: [1, 2], LIEAG: [0, 1] }); }); + it('takes the categories from the first stratifier, whatever its column is called', () => { + // Pins down: a composition whose category isn't `resultado` (the confirmation by biopsia_grado) is read too, and + // a stratifier can still be asked for by name. Fails if the reader goes back to a fixed name. + const renamed = { ...EU7, entry: EU7.entry.map(e => ({ resource: { ...e.resource, group: [{ ...e.resource.group[0], + stratifier: e.resource.group[0].stratifier!.map((s, i) => (i === 0 ? { ...s, code: [{ text: 'biopsia_grado' }] } : s)) }] } })) }; + expect(compositionFrom(renamed).categories).toEqual(compositionFrom(EU7).categories); + expect(() => compositionFrom(EU7, 'no_existe')).toThrow(InvalidMeasureReport); + }); + it('draws stacked bars, one segment per category', () => { // Pins down: the WebApp draws compositions from the same contract. Fails if a category stops being a trace. const figure = compositionFigure(compositionFrom(EU7), 'EU7'); @@ -118,12 +130,39 @@ describe('compositions', () => { }); }); +describe('durations', () => { + it('reads the samples measurable and measured, the median and the quartiles of each period', () => { + // Pins down: a duration's populations and its score with the quartiles as extensions. Fails if the WebApi's + // duration contract or its reading drifts. + expect(durationFrom(DIAS).points).toEqual([ + { period: '2025-S2', initial: 4, n: 2, q1: 70.25, median: 100.5, q3: 130.75 }, + ]); + expect(durationFrom(DIAS).lowerIsBetter).toBe(true); + }); + + it('draws a box per period from the served quartiles, without whiskers', () => { + // Pins down: the WebApp draws durations from the same contract. Fails if the box stops using the quartiles or + // starts drawing extremes it wasn't given. + const [box] = durationFigure(durationFrom(DIAS), 'Días a diagnóstico').data; + expect(box['type']).toBe('box'); + expect([box['q1'], box['median'], box['q3']]).toEqual([[70.25], [100.5], [130.75]]); + expect([box['lowerfence'], box['upperfence']]).toEqual([[70.25], [130.75]]); + }); + + it('rejects a duration measured without its median', () => { + // Pins down: a malformed answer fails loudly. Fails if the check on the score is dropped. + const [entry] = DIAS.entry; + const broken = { ...DIAS, entry: [{ resource: { ...entry.resource, group: [{ ...entry.resource.group[0], measureScore: undefined }] } }] }; + expect(() => durationFrom(broken)).toThrow(InvalidMeasureReport); + }); +}); + describe('KpisPage', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); it('draws every measure the WebApi lists, each from its reports', () => { - // Pins down: the page needs nothing per measure: it lists `/cacu/kpis` and draws proportions and compositions - // from the one contract. Fails if a scoring stops being drawn or the page starts naming measures. + // Pins down: the page needs nothing per measure: it lists `/cacu/kpis` and draws proportions, compositions + // and durations from the one contract. Fails if a scoring stops being drawn or the page starts naming measures. TestBed.overrideComponent(KpisPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); const fixture = TestBed.createComponent(KpisPage); fixture.componentInstance.ngOnInit(); @@ -132,14 +171,17 @@ describe('KpisPage', () => { { id: 'IND1', url: 'cacu/IND1', version: '0.3.2', scoring: 'proportion' }, { id: 'CACU_EU13', url: 'cacu/CACU_EU13', version: '0.3.2', scoring: 'proportion' }, { id: 'CACU_EU7', url: 'cacu/CACU_EU7', version: '0.3.3', scoring: 'composition' }, + { id: 'CACU_DIAS_TOMA_DIAGNOSTICO', url: 'cacu/CACU_DIAS_TOMA_DIAGNOSTICO', version: '0.2.3', scoring: 'continuous-variable' }, ]); http.expectOne(r => r.url === '/cacu/kpis/IND1').flush(IND1); http.expectOne(r => r.url === '/cacu/kpis/CACU_EU13').flush(EU13); http.expectOne(r => r.url === '/cacu/kpis/CACU_EU7').flush(EU7); + http.expectOne(r => r.url === '/cacu/kpis/CACU_DIAS_TOMA_DIAGNOSTICO').flush(DIAS); fixture.detectChanges(); expect(fixture.componentInstance.status()).toBe('ready'); - expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7']); + expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7', 'CACU_DIAS_TOMA_DIAGNOSTICO']); expect(fixture.componentInstance.figures()[2].figure.layout['barmode']).toBe('stack'); + expect(fixture.componentInstance.figures()[3].figure.data[0]['type']).toBe('box'); }); }); diff --git a/src/app/features/indicadores/measure-report.ts b/src/app/features/indicadores/measure-report.ts index 953b8f6..c14c88e 100644 --- a/src/app/features/indicadores/measure-report.ts +++ b/src/app/features/indicadores/measure-report.ts @@ -6,10 +6,11 @@ export interface CodeableConcept { coding?: { system?: string; code: string }[]; export interface ReportPopulation { code: CodeableConcept; count: number } export interface ReportStratum { value: CodeableConcept; population: ReportPopulation[]; measureScore?: { value: number } } export interface ReportStratifier { code: CodeableConcept[]; stratum: ReportStratum[] } +export interface Score { value: number; unit?: string; extension?: { url: string; valueDecimal?: number }[] } export interface ReportGroup { id?: string; population: ReportPopulation[]; - measureScore?: { value: number }; + measureScore?: Score; stratifier?: ReportStratifier[]; } export interface MeasureReport { @@ -112,10 +113,11 @@ export function proportionFigure(series: Series, title: string, stratum?: string } -/** A composition: per period, how many units fall in each category of its `resultado` stratifier. */ +/** A composition: per period, how many units fall in each category. The categories are the report's first + * stratifier (the WebApi puts them first, named after the category's column), or the one named `stratifier`. */ export interface CompositionSeries { measure: string; periods: string[]; categories: Record } -export function compositionFrom(bundle: MeasureReportBundle, stratifier = 'resultado'): CompositionSeries { +export function compositionFrom(bundle: MeasureReportBundle, stratifier?: string): CompositionSeries { if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) { throw new InvalidMeasureReport('Respuesta de KPI inválida'); } @@ -123,8 +125,9 @@ export function compositionFrom(bundle: MeasureReportBundle, stratifier = 'resul const periods = reports.map(r => periodLabel(r.period)); const categories: Record = {}; reports.forEach((report, i) => { - const found = report.group[0]?.stratifier?.find(s => s.code[0]?.text === stratifier); - if (!found) throw new InvalidMeasureReport(`Falta el estratificador ${stratifier}`); + const stratifiers = report.group[0]?.stratifier ?? []; + const found = stratifier === undefined ? stratifiers[0] : stratifiers.find(s => s.code[0]?.text === stratifier); + if (!found) throw new InvalidMeasureReport(`Falta el estratificador ${stratifier ?? 'de categorías'}`); for (const stratum of found.stratum) { const name = stratum.value.text ?? ''; (categories[name] ??= periods.map(() => 0))[i] = count(stratum.population, 'initial-population'); @@ -145,3 +148,45 @@ export function compositionFigure(series: CompositionSeries, title: string): Plo xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' } }, }; } + + +/** A duration: per period, the units measurable and measured and, if any was, the quartiles of their days. */ +export interface DurationPoint { period: string; initial: number; n: number; q1: number | null; median: number | null; q3: number | null } +export interface DurationSeries { measure: string; lowerIsBetter: boolean; points: DurationPoint[] } + +const quartile = (score: Score | undefined, name: string) => + score?.extension?.find(e => e.url.endsWith(`/${name}`))?.valueDecimal ?? null; + +export function durationFrom(bundle: MeasureReportBundle): DurationSeries { + if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) { + throw new InvalidMeasureReport('Respuesta de KPI inválida'); + } + const reports = bundle.entry.map(e => e.resource); + const points = reports.map(report => { + const [group] = report.group; + const n = count(group.population, 'measure-observation'); + const score = group.measureScore; + if (n > 0 && score === undefined) throw new InvalidMeasureReport('Falta la mediana'); + return { period: periodLabel(report.period), initial: count(group.population, 'initial-population'), n, + q1: quartile(score, 'q1'), median: score?.value ?? null, q3: quartile(score, 'q3') }; + }); + const lowerIsBetter = reports[0].improvementNotation?.coding?.some(c => c.code === 'decrease') ?? false; + return { measure: reports[0].measure, lowerIsBetter, points }; +} + +/** One box per period, from the served quartiles: first to third quartile and the median, no whiskers. */ +export function durationFigure(series: DurationSeries, title: string): PlotlyFigure { + const measured = series.points.filter(p => p.median !== null); + const data = [{ + type: 'box', name: 'Días', x: measured.map(p => p.period), + q1: measured.map(p => p.q1), median: measured.map(p => p.median), q3: measured.map(p => p.q3), + lowerfence: measured.map(p => p.q1), upperfence: measured.map(p => p.q3), + text: measured.map(p => `${p.period}
n = ${p.n} de ${p.initial}
mediana ${p.median} días`), hoverinfo: 'text', + }]; + const notes = series.lowerIsBetter ? [{ text: 'Menos días es mejor.', showarrow: false, xref: 'paper', yref: 'paper', x: 0, y: -0.2 }] : []; + return { + data, + layout: { title: { text: title }, showlegend: false, annotations: notes, + xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Días' }, rangemode: 'tozero' } }, + }; +} From 62cdb252ca5d9a272c9960f930a2824152ed7052 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 01:37:43 -0600 Subject: [PATCH 23/27] Measures read from //indicadores --- .../indicadores/measure-report.service.ts | 8 ++++---- .../indicadores/measure-report.spec.ts | 18 +++++++++--------- src/app/features/indicadores/measure-report.ts | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/app/features/indicadores/measure-report.service.ts b/src/app/features/indicadores/measure-report.service.ts index a26dd5d..d678df0 100644 --- a/src/app/features/indicadores/measure-report.service.ts +++ b/src/app/features/indicadores/measure-report.service.ts @@ -13,20 +13,20 @@ export class MeasureReportService { /** The measures the WebApi answers on request for the domain. */ list(dominio: Dominio) { - return this.http.get(`/${requireDominio(dominio)}/kpis`); + return this.http.get(`/${requireDominio(dominio)}/indicadores`); } composition(dominio: Dominio, indicador: string, periodos: string[]) { const params = new HttpParams().set('periodos', periodos.join(',')); return this.http - .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .get(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params }) .pipe(map((bundle): CompositionSeries => compositionFrom(bundle))); } duration(dominio: Dominio, indicador: string, periodos: string[]) { const params = new HttpParams().set('periodos', periodos.join(',')); return this.http - .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .get(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params }) .pipe(map((bundle): DurationSeries => durationFrom(bundle))); } @@ -35,7 +35,7 @@ export class MeasureReportService { if (cortes.evento) params = params.set('corte_evento', cortes.evento); if (cortes.conocimiento) params = params.set('corte_conocimiento', cortes.conocimiento); return this.http - .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .get(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params }) .pipe(map((bundle): Series => seriesFrom(bundle))); } } diff --git a/src/app/features/indicadores/measure-report.spec.ts b/src/app/features/indicadores/measure-report.spec.ts index efa9ae1..a4b5828 100644 --- a/src/app/features/indicadores/measure-report.spec.ts +++ b/src/app/features/indicadores/measure-report.spec.ts @@ -1,4 +1,4 @@ -// What this covers: reading the WebApi's FHIR `MeasureReport` bundles (`//kpis/`) into a series, drawing +// What this covers: reading the WebApi's FHIR `MeasureReport` bundles (`//indicadores/`) into a series, drawing // it here, the service that asks for it and the component that shows it. // Fixtures: `cacu_ind1_measure_report_bundle.json` (IND1, 2025-S1 and 2025-S2) and // `cacu_eu13_measure_report_bundle.json` (EU13, 2025-S1, with the `grupo_edad` stratifier) and @@ -83,7 +83,7 @@ describe('MeasureReportService and IndicadorMeasureReport', () => { // the URL or a parameter's name drifts from the WebApi's. const answer = firstValueFrom(TestBed.inject(MeasureReportService) .series('cacu', 'IND1', ['2025-S1', '2025-S2'], { evento: '2025-12-31' })); - const request = TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/kpis/IND1'); + const request = TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/indicadores/IND1'); expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('corte_evento')).toBe('2025-12-31'); expect(request.request.params.has('corte_conocimiento')).toBe(false); @@ -97,7 +97,7 @@ describe('MeasureReportService and IndicadorMeasureReport', () => { const fixture = TestBed.createComponent(IndicadorMeasureReport); Object.assign(fixture.componentInstance, { dominio: 'cacu', indicador: 'IND1', titulo: 'IND1', periodos: ['2025-S1', '2025-S2'] }); fixture.componentInstance.ngOnChanges(); - TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/kpis/IND1').flush(IND1); + TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/indicadores/IND1').flush(IND1); fixture.detectChanges(); expect(fixture.componentInstance.status()).toBe('ready'); expect(fixture.componentInstance.figure()?.data[0]['y']).toEqual([25, 25]); @@ -161,22 +161,22 @@ describe('KpisPage', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); it('draws every measure the WebApi lists, each from its reports', () => { - // Pins down: the page needs nothing per measure: it lists `/cacu/kpis` and draws proportions, compositions + // Pins down: the page needs nothing per measure: it lists `/cacu/indicadores` and draws proportions, compositions // and durations from the one contract. Fails if a scoring stops being drawn or the page starts naming measures. TestBed.overrideComponent(KpisPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); const fixture = TestBed.createComponent(KpisPage); fixture.componentInstance.ngOnInit(); const http = TestBed.inject(HttpTestingController); - http.expectOne('/cacu/kpis').flush([ + http.expectOne('/cacu/indicadores').flush([ { id: 'IND1', url: 'cacu/IND1', version: '0.3.2', scoring: 'proportion' }, { id: 'CACU_EU13', url: 'cacu/CACU_EU13', version: '0.3.2', scoring: 'proportion' }, { id: 'CACU_EU7', url: 'cacu/CACU_EU7', version: '0.3.3', scoring: 'composition' }, { id: 'CACU_DIAS_TOMA_DIAGNOSTICO', url: 'cacu/CACU_DIAS_TOMA_DIAGNOSTICO', version: '0.2.3', scoring: 'continuous-variable' }, ]); - http.expectOne(r => r.url === '/cacu/kpis/IND1').flush(IND1); - http.expectOne(r => r.url === '/cacu/kpis/CACU_EU13').flush(EU13); - http.expectOne(r => r.url === '/cacu/kpis/CACU_EU7').flush(EU7); - http.expectOne(r => r.url === '/cacu/kpis/CACU_DIAS_TOMA_DIAGNOSTICO').flush(DIAS); + http.expectOne(r => r.url === '/cacu/indicadores/IND1').flush(IND1); + http.expectOne(r => r.url === '/cacu/indicadores/CACU_EU13').flush(EU13); + http.expectOne(r => r.url === '/cacu/indicadores/CACU_EU7').flush(EU7); + http.expectOne(r => r.url === '/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO').flush(DIAS); fixture.detectChanges(); expect(fixture.componentInstance.status()).toBe('ready'); expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7', 'CACU_DIAS_TOMA_DIAGNOSTICO']); diff --git a/src/app/features/indicadores/measure-report.ts b/src/app/features/indicadores/measure-report.ts index c14c88e..27d6eb2 100644 --- a/src/app/features/indicadores/measure-report.ts +++ b/src/app/features/indicadores/measure-report.ts @@ -1,6 +1,6 @@ import { PlotlyFigure } from './indicadores.models'; -/** The part of FHIR R4's `MeasureReport` the WebApi's `//kpis/` serves: one group, its populations, +/** The part of FHIR R4's `MeasureReport` the WebApi's `//indicadores/` serves: one group, its populations, * its score and its strata. */ export interface CodeableConcept { coding?: { system?: string; code: string }[]; text?: string } export interface ReportPopulation { code: CodeableConcept; count: number } From 5807f218b103b8edfc9129391ab09fd4c286e3ef Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 14:28:04 -0600 Subject: [PATCH 24/27] Add TEA status measure view --- src/app/app.routes.ts | 6 +++ .../indicadores/tea-status-page.spec.ts | 24 +++++++++ .../features/indicadores/tea-status-page.ts | 53 +++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 src/app/features/indicadores/tea-status-page.spec.ts create mode 100644 src/app/features/indicadores/tea-status-page.ts diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 2249119..feed61d 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -6,6 +6,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page'). export const routes: Routes = [ { path: '', component: Home, title: 'Análisis de información | ISSSTELEON' }, + { + path: 'indicadores/tea-estatus', + title: 'Casos por estatus | ISSSTELEON', + loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage), + data: { workspace: true, breadcrumb: 'Casos por estatus' }, + }, { path: 'conectar', title: 'Conectar datos | ISSSTELEON', diff --git a/src/app/features/indicadores/tea-status-page.spec.ts b/src/app/features/indicadores/tea-status-page.spec.ts new file mode 100644 index 0000000..74ac0c0 --- /dev/null +++ b/src/app/features/indicadores/tea-status-page.spec.ts @@ -0,0 +1,24 @@ +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { TeaStatusPage } from './tea-status-page'; + +describe('TeaStatusPage', () => { + it('shows the stages in a FHIR report and reports a failed query', () => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + const component = TestBed.createComponent(TeaStatusPage).componentInstance; + const http = TestBed.inject(HttpTestingController); + component.consultar(); + const request = http.expectOne('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure?periodo=2025-S1'); + request.flush({ group: [{ population: [{ count: 6 }], stratifier: [{ stratum: [ + { value: { coding: [{ code: 'SOLO_MCHAT' }] }, population: [{ count: 2 }] }, + ] }] }] }); + expect(component.total()).toBe(6); + expect(component.filas()).toEqual([{ codigo: 'SOLO_MCHAT', nombre: 'M-CHAT', cantidad: 2 }]); + component.consultar(); + http.expectOne('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure?periodo=2025-S1') + .flush({}, { status: 404, statusText: 'Not Found' }); + expect(component.estado()).toBe('error'); + http.verify(); + }); +}); diff --git a/src/app/features/indicadores/tea-status-page.ts b/src/app/features/indicadores/tea-status-page.ts new file mode 100644 index 0000000..99b7b31 --- /dev/null +++ b/src/app/features/indicadores/tea-status-page.ts @@ -0,0 +1,53 @@ +import { HttpClient, HttpParams } from '@angular/common/http'; +import { Component, inject, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; + +interface Population { count?: number } +interface Stratum { value?: { coding?: { code?: string; display?: string }[] }; population?: Population[] } +interface Report { group?: { population?: Population[]; stratifier?: { stratum?: Stratum[] }[] }[] } + +@Component({ + selector: 'app-tea-status-page', + imports: [FormsModule], + template: ` +

Casos por estatus

+

Consulte la etapa alcanzada por las niñas y los niños en el periodo seleccionado.

+
+ + +
+ @if (estado() === 'cargando') {

Consultando información…

} + @if (estado() === 'error') {

No fue posible consultar el periodo. Verifique el periodo e intente de nuevo.

} + @if (estado() === 'listo') { +

Total: {{ total() }}

+ @if (filas().length === 0) {

No hay casos para este periodo.

} + @else {
    @for (fila of filas(); track fila.codigo) {
  • {{ fila.nombre }}: {{ fila.cantidad }}
  • }
} + } + `, +}) +export class TeaStatusPage { + private readonly http = inject(HttpClient); + periodo = '2025-S1'; + readonly estado = signal<'inicial' | 'cargando' | 'listo' | 'error'>('inicial'); + readonly total = signal(0); + readonly filas = signal<{ codigo: string; nombre: string; cantidad: number }[]>([]); + + consultar() { + this.estado.set('cargando'); + this.http.get('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure', { + params: new HttpParams().set('periodo', this.periodo), + }).subscribe({ + next: report => { + const group = report.group?.[0]; + this.total.set(group?.population?.[0]?.count ?? 0); + const nombres: Record = { SOLO_MCHAT: 'M-CHAT', PSICOLOGIA: 'Psicología', NEUROPEDIATRIA: 'Neuropediatría', EEG: 'EEG' }; + this.filas.set((group?.stratifier?.[0]?.stratum ?? []).map(s => { + const codigo = s.value?.coding?.[0]?.code ?? ''; + return { codigo, nombre: nombres[codigo] ?? s.value?.coding?.[0]?.display ?? codigo, cantidad: s.population?.[0]?.count ?? 0 }; + })); + this.estado.set('listo'); + }, + error: () => this.estado.set('error'), + }); + } +} From c509cb7f8730ee125c7df94a5153b5410e475316 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 14:28:04 -0600 Subject: [PATCH 25/27] Connect TEA screening views to FHIR --- src/app/app.routes.ts | 9 +- .../features/indicadores/tea-status-page.html | 69 ++++++ .../features/indicadores/tea-status-page.scss | 13 ++ .../indicadores/tea-status-page.spec.ts | 75 +++++-- .../features/indicadores/tea-status-page.ts | 212 ++++++++++++++---- 5 files changed, 319 insertions(+), 59 deletions(-) create mode 100644 src/app/features/indicadores/tea-status-page.html create mode 100644 src/app/features/indicadores/tea-status-page.scss diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index feed61d..9857d72 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -7,11 +7,12 @@ const loadIndicadores = () => import('./features/indicadores/indicadores-page'). export const routes: Routes = [ { path: '', component: Home, title: 'Análisis de información | ISSSTELEON' }, { - path: 'indicadores/tea-estatus', - title: 'Casos por estatus | ISSSTELEON', + path: 'indicadores/tea', + title: 'Indicadores TEA | ISSSTELEON', loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage), - data: { workspace: true, breadcrumb: 'Casos por estatus' }, + data: { workspace: true, breadcrumb: 'Indicadores TEA' }, }, + { path: 'indicadores/tea-estatus', pathMatch: 'full', redirectTo: 'indicadores/tea' }, { path: 'conectar', title: 'Conectar datos | ISSSTELEON', @@ -39,7 +40,7 @@ export const routes: Routes = [ data: { workspace: true, breadcrumb: 'Indicadores' }, }, { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, - ...DOMINIOS.map(dominio => ({ + ...DOMINIOS.filter(dominio => dominio !== 'tea').map(dominio => ({ path: `indicadores/${dominio}`, title: 'Indicadores | ISSSTELEON', data: { workspace: true, breadcrumb: 'Indicadores', dominio }, diff --git a/src/app/features/indicadores/tea-status-page.html b/src/app/features/indicadores/tea-status-page.html new file mode 100644 index 0000000..74e5ea1 --- /dev/null +++ b/src/app/features/indicadores/tea-status-page.html @@ -0,0 +1,69 @@ +
+
Trastorno del espectro autista, investigación

Indicadores

Explore la información del tamizaje.

+ + + @if (section() !== 'seguimiento') { +
+

{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}

+
+ @if (section() === 'resumen') { } + @else { + + + } + + + +
+ @if (measureState() === 'cargando' || measureState() === 'inicial') {

Consultando indicadores…

} + @if (measureState() === 'error') {

{{ measureError() }}

} + @if (measureState() === 'listo' && reports().length === 0) {

No hay indicadores para la selección.

} + @for (report of reports(); track $index) { + @if (measureState() === 'listo') {

{{ title(report) }}

{{ report.period?.start }} a {{ report.period?.end }}

+ @if (rows(report).length === 0) {

Sin datos para el periodo.

} + @else {
@for (row of rows(report); track $index) {
{{ row.label }}
{{ row.value }}
}
} +
} + } +
+ } +
+

Seguimiento

Consulte los episodios según la fecha de corte y los filtros seleccionados.

+
+ + + + + + + + + @if (alterationsAvailable() && alterationTypes().length) { } + +
+ @if (episodeState() === 'cargando') {

Consultando seguimiento…

} + @if (episodeState() === 'error') {

{{ episodeError() }}

} + @if (episodeState() === 'listo') { +

{{ episodeTotal() }} episodios

+ @if (episodes().length === 0) {

No hay episodios para la selección.

} + @else { + @for (e of episodes(); track e.id) { } +
PacienteEtapaFecha de etapaEstado
{{ patientId(e) }}{{ stage(e) }}{{ stageDate(e) }}{{ e.status === 'finished' ? 'Finalizado' : 'En seguimiento' }}
} +
Página {{ page + 1 }}
+ } +
+ @if (section() === 'seguimiento' && selected()) { +

Ficha del paciente

{{ selected() }}

La ficha muestra la información disponible a la fecha actual.

+ @if (patientState() === 'cargando') {

Consultando ficha…

} + @if (patientState() === 'error') {

{{ patientError() }}

} + @if (patientState() === 'listo') { +

ADOS-2

@if (ados(); as ados) {

Fecha: {{ ados.effectiveDateTime }}

@for (c of ados.component; track $index) {
{{ c.code.coding?.[0]?.display || c.code.coding?.[0]?.code }}
{{ componentValue(c) }}
}
} @else {

Sin información de ADOS-2.

}
+

EEG del estudio

@if (eeg(); as eeg) {

Fecha: {{ eeg.effectiveDateTime }}

Calidad: {{ eegQuality() }}

Duración: {{ eegExtension('duracion-min') }} minutos. Canales: {{ eegExtension('canales') }}.

@if (eeg.conclusion) {

{{ eeg.conclusion }}

}
@for (o of quality(); track o.id) {
{{ o.code.coding?.[0]?.display }}
{{ observationValue(o) }} ({{ qualityStatus(o) }})
}
} @else {

Sin información de EEG.

}
+ @if (alterationsAvailable() && alterations().length) {

Métricas del EEG

@for (o of alterations(); track o.id) {
{{ o.code.coding?.[0]?.display }}
{{ observationValue(o) }}
}
} + } +
+ } +
diff --git a/src/app/features/indicadores/tea-status-page.scss b/src/app/features/indicadores/tea-status-page.scss new file mode 100644 index 0000000..4e56781 --- /dev/null +++ b/src/app/features/indicadores/tea-status-page.scss @@ -0,0 +1,13 @@ +.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; } +button { border: 1px solid #216b56; border-radius: .3rem; background: #fff; color: #165a47; padding: .55rem .8rem; cursor: pointer; } +button[aria-current="page"], button[type="submit"] { background: #216b56; color: white; } +button:disabled { opacity: .5; cursor: default; } +label { display: grid; gap: .25rem; font-size: .9rem; } +input, select { padding: .45rem; border: 1px solid #8ba09a; border-radius: .25rem; } +.card { border: 1px solid #d5e0dc; border-radius: .5rem; padding: 1rem; margin: 1rem 0; background: #fff; } +dl div { display: flex; gap: 1rem; justify-content: space-between; border-bottom: 1px solid #edf1ef; padding: .3rem 0; } dd { margin: 0; font-weight: 600; } +table { width: 100%; border-collapse: collapse; } th, td { text-align: left; padding: .55rem; border-bottom: 1px solid #d5e0dc; } diff --git a/src/app/features/indicadores/tea-status-page.spec.ts b/src/app/features/indicadores/tea-status-page.spec.ts index 74ac0c0..9f23683 100644 --- a/src/app/features/indicadores/tea-status-page.spec.ts +++ b/src/app/features/indicadores/tea-status-page.spec.ts @@ -1,24 +1,69 @@ import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; +import { provideRouter } from '@angular/router'; import { TeaStatusPage } from './tea-status-page'; -describe('TeaStatusPage', () => { - it('shows the stages in a FHIR report and reports a failed query', () => { - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); - const component = TestBed.createComponent(TeaStatusPage).componentInstance; +const tag = { tag: [{ system: 'https://isssteleon.org/fhir/CodeSystem/etiqueta', code: 'simulado' }] }; +const episode = (id: string) => ({ resourceType: 'EpisodeOfCare', id, meta: tag, patient: { reference: `Patient/${id}` }, type: [{ coding: [{ code: 'SOLO_MCHAT' }] }] }); +const measure = { resourceType: 'Measure', id: 'M28-casos-por-estado', title: 'Casos por estatus', url: 'https://isssteleon.org/fhir/Measure/M28-casos-por-estado' }; +const bundle = (...items: any[]) => ({ resourceType: 'Bundle', total: items.length, entry: items.map(resource => ({ resource })) }); + +describe('TEA FHIR journey', () => { + function setup() { + TestBed.configureTestingModule({ providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + const fixture = TestBed.createComponent(TeaStatusPage); + const c = fixture.componentInstance; const http = TestBed.inject(HttpTestingController); - component.consultar(); - const request = http.expectOne('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure?periodo=2025-S1'); - request.flush({ group: [{ population: [{ count: 6 }], stratifier: [{ stratum: [ - { value: { coding: [{ code: 'SOLO_MCHAT' }] }, population: [{ count: 2 }] }, - ] }] }] }); - expect(component.total()).toBe(6); - expect(component.filas()).toEqual([{ codigo: 'SOLO_MCHAT', nombre: 'M-CHAT', cantidad: 2 }]); - component.consultar(); - http.expectOne('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure?periodo=2025-S1') - .flush({}, { status: 404, statusText: 'Not Found' }); - expect(component.estado()).toBe('error'); + http.expectOne('/tea/fhir/Measure').flush(bundle(measure)); + http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] }); + return { c, http }; + } + it('distinguishes zero, missing and masked values and requests the historical periods', () => { + const { c, http } = setup(); + expect(c.value({ count: 0 }, 'count')).toBe('0'); + expect(c.value({}, 'count')).toBe('Sin dato'); + expect(c.value({ _count: { extension: [{ valueCode: 'masked' }] } }, 'count')).toBe('Dato suprimido'); + c.changeSection('historico'); + const req = http.expectOne(r => r.url === '/tea/fhir/MeasureReport'); + expect(req.request.params.get('periodo')).toBe('2025-01,2025-02,2025-03'); + req.flush(bundle()); + expect(c.reports()).toEqual([]); + http.verify(); + }); + it('retains filters and page and rejects a late patient response', () => { + const { c, http } = setup(); + c.filters.stage = 'PSICOLOGIA'; c.filters.cutoff = '2025-12-31'; c.filters.cssMin = null as unknown as string; c.page = 1; c.changeSection('seguimiento'); + const list = http.expectOne(r => r.url.endsWith('/EpisodeOfCare')); + expect(list.request.params.get('etapa')).toBe('PSICOLOGIA'); + expect(list.request.params.get('_offset')).toBe('5'); + expect(list.request.params.has('css')).toBe(false); + list.flush({ ...bundle(episode('a'), episode('b')), total: 8 }); + c.openPatient(episode('a')); const a = http.expectOne(r => r.url.includes('/Patient/a/')); + c.openPatient(episode('b')); const b = http.expectOne(r => r.url.includes('/Patient/b/')); + b.flush(bundle({ resourceType: 'Patient', id: 'b', meta: tag })); + a.flush(bundle({ resourceType: 'Patient', id: 'a', meta: tag })); + expect(c.selected()).toBe('b'); expect(c.patientResources()[0].id).toBe('b'); + c.back(); expect(c.page).toBe(1); expect(c.filters.stage).toBe('PSICOLOGIA'); + http.verify(); + }); + it('rejects an untagged response and shows the OperationOutcome error', () => { + const { c, http } = setup(); + c.changeSection('seguimiento'); + http.expectOne(r => r.url.endsWith('/EpisodeOfCare')).flush(bundle({ ...episode('a'), meta: {} })); + expect(c.episodeState()).toBe('error'); + c.openPatient(episode('a')); + http.expectOne(r => r.url.includes('/Patient/a/')).flush({ issue: [{ diagnostics: 'Paciente no encontrado' }] }, { status: 404, statusText: 'Not Found' }); + expect(c.patientError()).toBe('Paciente no encontrado'); + http.verify(); + }); + it('shows alteration groups only when the catalog offers M30', () => { + const { c, http } = setup(); + expect(c.alterationsAvailable()).toBe(false); + c.measures.set([measure, { id: 'M30-resultado-eeg', url: 'm30', scoring: { coding: [{ code: 'proportion' }] } }]); + expect(c.alterationsAvailable()).toBe(true); + const rows = c.rows({ measure: 'm30', group: [{ population: [] }, { code: { coding: [{ code: 'ritmo', display: 'Ritmo' }] }, population: [{ code: { coding: [{ code: 'numerator' }] }, count: 0 }] }] }); + expect(rows).toContainEqual({ label: 'Ritmo — Numerador', value: '0' }); http.verify(); }); }); diff --git a/src/app/features/indicadores/tea-status-page.ts b/src/app/features/indicadores/tea-status-page.ts index 99b7b31..b6927ab 100644 --- a/src/app/features/indicadores/tea-status-page.ts +++ b/src/app/features/indicadores/tea-status-page.ts @@ -1,53 +1,185 @@ import { HttpClient, HttpParams } from '@angular/common/http'; -import { Component, inject, signal } from '@angular/core'; +import { Component, ElementRef, inject, OnDestroy, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; +import { RouterLink } from '@angular/router'; +import { forkJoin, Subscription } from 'rxjs'; -interface Population { count?: number } -interface Stratum { value?: { coding?: { code?: string; display?: string }[] }; population?: Population[] } -interface Report { group?: { population?: Population[]; stratifier?: { stratum?: Stratum[] }[] }[] } +type Resource = any; +type Section = 'resumen' | 'historico' | 'seguimiento'; +type State = 'inicial' | 'cargando' | 'listo' | 'error'; +const stages: Record = { SOLO_MCHAT: 'Solo M-CHAT', PSICOLOGIA: 'Hasta evaluación psicológica', NEUROPEDIATRIA: 'Hasta evaluación neuropediátrica', EEG: 'Con EEG' }; +const populations: Record = { 'initial-population': 'Total', numerator: 'Numerador', denominator: 'Denominador', 'denominator-exclusion': 'Excluidos del denominador', 'measure-observation': 'Con valor', 'measure-population-exclusion': 'Sin valor' }; +const code = (value: Resource) => value?.coding?.[0]?.code ?? ''; +const text = (value: Resource) => value?.coding?.[0]?.display ?? value?.text ?? code(value); +const resources = (bundle: Resource): Resource[] => (bundle?.entry ?? []).map((entry: Resource) => entry.resource); +const simulated = (resource: Resource) => resource?.meta?.tag?.some((tag: Resource) => tag.system === 'https://isssteleon.org/fhir/CodeSystem/etiqueta' && tag.code === 'simulado'); @Component({ selector: 'app-tea-status-page', - imports: [FormsModule], - template: ` -

Casos por estatus

-

Consulte la etapa alcanzada por las niñas y los niños en el periodo seleccionado.

-
- - -
- @if (estado() === 'cargando') {

Consultando información…

} - @if (estado() === 'error') {

No fue posible consultar el periodo. Verifique el periodo e intente de nuevo.

} - @if (estado() === 'listo') { -

Total: {{ total() }}

- @if (filas().length === 0) {

No hay casos para este periodo.

} - @else {
    @for (fila of filas(); track fila.codigo) {
  • {{ fila.nombre }}: {{ fila.cantidad }}
  • }
} - } - `, + imports: [FormsModule, RouterLink], + templateUrl: './tea-status-page.html', + styleUrl: './tea-status-page.scss', }) -export class TeaStatusPage { +export class TeaStatusPage implements OnDestroy { private readonly http = inject(HttpClient); + private readonly element = inject>(ElementRef); + private requests: Subscription[] = []; + private revision = { measures: 0, episodes: 0, patient: 0 }; + readonly section = signal
('resumen'); + readonly measures = signal([]); + readonly alterationTypes = signal([]); + readonly reports = signal([]); + readonly measureState = signal('inicial'); + readonly measureError = signal(''); + readonly episodes = signal([]); + readonly episodeTotal = signal(0); + readonly episodeState = signal('inicial'); + readonly episodeError = signal(''); + readonly selected = signal(null); + readonly patientResources = signal([]); + readonly patientState = signal('inicial'); + readonly patientError = signal(''); periodo = '2025-S1'; - readonly estado = signal<'inicial' | 'cargando' | 'listo' | 'error'>('inicial'); - readonly total = signal(0); - readonly filas = signal<{ codigo: string; nombre: string; cantidad: number }[]>([]); + historyPeriods = '2025-01,2025-02,2025-03'; + measureId = 'M28-casos-por-estado'; + eventCutoff = ''; + knowledgeCutoff = ''; + page = 0; + pageSize = 5; + filters = { since: '', cutoff: '', status: '', stage: '', stageFrom: '', stageTo: '', age: '', mchatMin: '', mchatMax: '', cssMin: '', cssMax: '', eeg: '', alteration: '' }; + readonly stages = stages; - consultar() { - this.estado.set('cargando'); - this.http.get('/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure', { - params: new HttpParams().set('periodo', this.periodo), - }).subscribe({ - next: report => { - const group = report.group?.[0]; - this.total.set(group?.population?.[0]?.count ?? 0); - const nombres: Record = { SOLO_MCHAT: 'M-CHAT', PSICOLOGIA: 'Psicología', NEUROPEDIATRIA: 'Neuropediatría', EEG: 'EEG' }; - this.filas.set((group?.stratifier?.[0]?.stratum ?? []).map(s => { - const codigo = s.value?.coding?.[0]?.code ?? ''; - return { codigo, nombre: nombres[codigo] ?? s.value?.coding?.[0]?.display ?? codigo, cantidad: s.population?.[0]?.count ?? 0 }; - })); - this.estado.set('listo'); + constructor() { + this.requests.push(this.http.get('/tea/fhir/Measure').subscribe({ + next: bundle => { + this.measures.set(resources(bundle).filter(m => /^M(2[1-9]|30)-/.test(m.id))); + if (this.alterationsAvailable()) this.requests.push(this.http.get('/tea/fhir/CodeSystem/tea-eeg-metrica').subscribe({ next: system => this.alterationTypes.set(system.concept ?? []), error: () => this.alterationTypes.set([]) })); + this.loadSummary(); }, - error: () => this.estado.set('error'), - }); + error: () => { this.measureState.set('error'); this.measureError.set('No fue posible cargar los indicadores.'); }, + })); } + ngOnDestroy() { this.requests.forEach(s => s.unsubscribe()); } + changeSection(section: Section) { + this.section.set(section); + if (section === 'resumen') this.loadSummary(); + if (section === 'historico') this.loadHistory(); + if (section === 'seguimiento' && this.episodeState() === 'inicial') this.loadEpisodes(); + } + private cutoffs(params: HttpParams): HttpParams { + if (this.eventCutoff) params = params.set('corte_evento', this.eventCutoff); + if (this.knowledgeCutoff) params = params.set('corte_conocimiento', new Date(this.knowledgeCutoff).toISOString()); + return params; + } + loadSummary() { + const token = ++this.revision.measures; + const measures = this.measures(); + if (!measures.length) { this.measureState.set('listo'); this.reports.set([]); return; } + this.measureState.set('cargando'); + const params = this.cutoffs(new HttpParams().set('periodo', this.periodo)); + this.requests.push(forkJoin(measures.map(m => this.http.get(`/tea/fhir/Measure/${encodeURIComponent(m.id)}/$evaluate-measure`, { params }))).subscribe({ + next: reports => { if (token === this.revision.measures) { this.reports.set(reports); this.measureState.set('listo'); } }, + error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } }, + })); + } + loadHistory() { + const token = ++this.revision.measures; + const measure = this.measures().find(m => m.id === this.measureId); + if (!measure) { this.measureState.set('error'); this.measureError.set('Seleccione un indicador disponible.'); return; } + this.measureState.set('cargando'); + const params = this.cutoffs(new HttpParams().set('measure', measure.url).set('periodo', this.historyPeriods.replace(/\s/g, '')).set('_count', 200)); + this.requests.push(this.http.get('/tea/fhir/MeasureReport', { params }).subscribe({ + next: bundle => { if (token === this.revision.measures) { const found = resources(bundle); if (bundle.total > found.length) { this.measureError.set('Seleccione como máximo 200 periodos.'); this.measureState.set('error'); return; } this.reports.set(found); this.measureState.set('listo'); } }, + error: e => { if (token === this.revision.measures) { this.measureError.set(this.errorText(e)); this.measureState.set('error'); } }, + })); + } + title(report: Resource) { return this.measures().find(m => report.measure?.split('|')[0] === m.url)?.title ?? report.measure; } + rows(report: Resource): { label: string; value: string }[] { + const group = report.group?.[0]; + if (!group) return []; + const rows = (group.population ?? []).map((p: Resource) => ({ label: populations[code(p.code)] ?? text(p.code), value: this.value(p, 'count') })); + const measure = this.measures().find(m => report.measure?.split('|')[0] === m.url); + if (code(measure?.scoring) !== 'cohort') rows.push({ label: 'Resultado', value: group.measureScore ? this.score(group.measureScore) : 'Sin dato' }); + for (const extension of group.measureScore?.extension ?? []) { + if (extension.url?.endsWith('/q1') || extension.url?.endsWith('/q3')) rows.push({ label: extension.url.endsWith('/q1') ? 'Primer cuartil' : 'Tercer cuartil', value: `${extension.valueDecimal} días` }); + } + for (const stratum of group.stratifier?.[0]?.stratum ?? []) { + const name = code(stratum.value); + const label = stages[name] ?? ({ '16_23': '16 a 23 meses', '24_29': '24 a 29 meses', '30_36': '30 a 36 meses' } as Record)[name] ?? text(stratum.value); + if (code(measure?.scoring) === 'cohort') rows.push({ label, value: this.value(stratum.population?.[0], 'count') }); + else { + for (const p of stratum.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') }); + rows.push({ label: `${label} — resultado`, value: stratum.measureScore ? this.score(stratum.measureScore) : 'Sin dato' }); + } + } + for (const extra of report.group?.slice(1) ?? []) { + const label = text(extra.code) || 'Grupo'; + for (const p of extra.population ?? []) rows.push({ label: `${label} — ${populations[code(p.code)] ?? text(p.code)}`, value: this.value(p, 'count') }); + rows.push({ label: `${label} — resultado`, value: extra.measureScore ? this.score(extra.measureScore) : 'Sin dato' }); + } + return rows; + } + value(value: Resource, field: string): string { + if (value?.[`_${field}`]?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido'; + return value?.[field] == null ? 'Sin dato' : String(value[field]); + } + score(score: Resource): string { + if (score?._value?.extension?.some((e: Resource) => e.valueCode === 'masked')) return 'Dato suprimido'; + if (score?.value == null) return 'Sin dato'; + return score.unit === 'd' ? `${score.value} días` : `${(100 * score.value).toFixed(1)} %`; + } + private errorText(error: Resource) { return error?.error?.issue?.[0]?.diagnostics ?? 'No fue posible consultar la información. Intente de nuevo.'; } + applyFilters() { this.page = 0; this.loadEpisodes(); } + loadEpisodes() { + const token = ++this.revision.episodes; + this.episodeState.set('cargando'); + let p = new HttpParams().set('_count', this.pageSize).set('_offset', this.page * this.pageSize).set('_include', '*'); + const f = this.filters; + for (const [key, val] of [['status', f.status], ['etapa', f.stage], ['grupo-edad', f.age], ['resultado-eeg', f.eeg]] as const) if (val) p = p.set(key, val); + if (this.alterationsAvailable() && f.alteration) p = p.set('alteracion', f.alteration); + for (const [key, prefix, val] of [['date', 'ge', f.since], ['date', 'le', f.cutoff], ['fecha-etapa', 'ge', f.stageFrom], ['fecha-etapa', 'le', f.stageTo], ['mchat', 'ge', f.mchatMin], ['mchat', 'le', f.mchatMax], ['css', 'ge', f.cssMin], ['css', 'le', f.cssMax]] as const) if (val != null && val !== '') p = p.append(key, prefix + val); + this.requests.push(this.http.get('/tea/fhir/EpisodeOfCare', { params: p }).subscribe({ + next: bundle => { + if (token !== this.revision.episodes) return; + const found = resources(bundle); + if (found.some(r => !simulated(r))) { this.episodeError.set('La información recibida no está identificada como datos simulados.'); this.episodeState.set('error'); return; } + this.episodes.set(found.filter(r => r.resourceType === 'EpisodeOfCare')); this.episodeTotal.set(bundle.total ?? 0); this.episodeState.set('listo'); + }, + error: e => { if (token === this.revision.episodes) { this.episodeError.set(this.errorText(e)); this.episodeState.set('error'); } }, + })); + } + stage(e: Resource) { const value = code(e.type?.[0]); return stages[value] ?? value ?? 'Sin dato'; } + stageDate(e: Resource) { return e.extension?.find((x: Resource) => x.url.endsWith('/fecha-etapa'))?.valueDate ?? 'Sin dato'; } + patientId(e: Resource): string { return e.patient?.reference?.startsWith('Patient/') ? e.patient.reference.slice(8) : ''; } + openPatient(e: Resource) { + const id = this.patientId(e); + if (!id) { this.episodeError.set('El episodio no identifica a un paciente.'); this.episodeState.set('error'); return; } + const token = ++this.revision.patient; + this.selected.set(id); this.patientState.set('cargando'); this.patientResources.set([]); + this.requests.push(this.http.get(`/tea/fhir/Patient/${encodeURIComponent(id)}/$resumen-tea`).subscribe({ + next: bundle => { + if (token !== this.revision.patient || this.selected() !== id) return; + const found = resources(bundle); + if (!found.some(r => r.resourceType === 'Patient' && r.id === id) || found.some(r => !simulated(r) || (r.resourceType === 'Patient' && r.id !== id) || (r.subject?.reference && r.subject.reference !== `Patient/${id}`))) { + this.patientError.set('No se pudo verificar la identidad o el origen de la ficha.'); this.patientState.set('error'); return; + } + this.patientResources.set(found); this.patientState.set('listo'); + }, + error: e => { if (token === this.revision.patient && this.selected() === id) { this.patientError.set(this.errorText(e)); this.patientState.set('error'); } }, + })); + } + back() { + const id = this.selected(); ++this.revision.patient; this.selected.set(null); + setTimeout(() => this.element.nativeElement.querySelector(`[data-patient="${id}"]`)?.focus()); + } + 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'; } + 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_')); } + 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'); } } From b42428b06873a5c7a5c548473b96d36b1a81304d Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 13 Nov 2026 19:38:36 -0600 Subject: [PATCH 26/27] TEA: the EEG result measure draws one bar per alteration --- .../indicadores/indicador-figure-panel.ts | 10 +++ .../indicadores-c1-alteraciones.spec.ts | 63 ++++++++++++++++ .../indicadores-c1-alteraciones.ts | 71 +++++++++++++++++++ .../indicadores/indicadores-fhir.spec.ts | 24 +++++++ .../indicadores-figure-labels.spec.ts | 1 + .../indicadores/indicadores-figure-labels.ts | 1 + 6 files changed, 170 insertions(+) create mode 100644 src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts create mode 100644 src/app/features/indicadores/indicadores-c1-alteraciones.ts diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 90ab335..a6bb41f 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -15,6 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2'; import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; +import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; @@ -258,6 +259,15 @@ export class IndicadorFigurePanel implements OnChanges { emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined }; })); } + if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) { + return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => { + const adapted = c1AlterationFigure(data, selection); + if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState; + return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes, + highlight: adapted.highlight, ownLayout: true, plotHeight: 400, + emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined }; + })); + } if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) { // Both panels, KPI and numeric table share the exact same transport key. // Do not catch /datos errors here: a backend failure is a real error state. diff --git a/src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts b/src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts new file mode 100644 index 0000000..3c4e2fd --- /dev/null +++ b/src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts @@ -0,0 +1,63 @@ +import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones'; +import { FigureSelection, IndicadorDatos } from './indicadores.models'; + +const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({ + periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null, + n_sin_evento: denominador - numerador, n_excluido: 0, ...extra, +}); +const datos = (filas: Record[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({ + id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente', + tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [], + grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' }, + grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas, +}); +const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; + +describe('Barras por alteración para C1', () => { + it('solo aplica a C1 con la figura por alteración', () => { + expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true); + expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false); + expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false); + }); + it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => { + const result = c1AlterationFigure(datos(), selection); + if (result.status !== 'supported') throw new Error(result.reason); + const [trace] = result.figure.data as Record[]; + expect(result.figure.data.length).toBe(1); + expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']); + expect(trace['y']).toEqual([55, 25, 0]); + expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']); + expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]); + expect(result.total).toBe(20); + expect(result.notes).toEqual(['Datos ficticios.']); + expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']); + expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2'); + }); + it('varios periodos se dibujan lado a lado, uno por serie', () => { + const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' }); + const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] }; + const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] }); + if (result.status !== 'supported') throw new Error(result.reason); + const traces = result.figure.data as Record[]; + expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']); + expect(traces[0]['y']).toEqual([25, 12.5, 12.5]); + expect(result.figure.layout['showlegend']).toBe(true); + expect(result.total).toBe(28); + expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]); + }); + it('un periodo sin niños con EEG bueno no dibuja ceros', () => { + const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection); + if (result.status !== 'supported') throw new Error(result.reason); + expect((result.figure.data[0] as Record)['y']).toEqual([null, null, null]); + expect(result.total).toBe(0); + }); + it('rechaza datos que no son los grupos por alteración de la selección', () => { + expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported'); + expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported'); + expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c1-alteraciones.ts b/src/app/features/indicadores/indicadores-c1-alteraciones.ts new file mode 100644 index 0000000..8f95020 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c1-alteraciones.ts @@ -0,0 +1,71 @@ +import { percentNumber } from './indicadores-format'; +import { FigureHighlight } from './indicadores-highlight'; +import { C2_PALETTE, c2Theme } from './indicadores-c2-palette'; +import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; + +// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with +// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL +// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side. +export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion'; +const TOTAL = 'TOTAL'; +const ANY_LABEL = 'Alguna alteración'; + +export type C1AlterationResult = { status: 'unsupported'; reason: string } + | { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] }; +export function c1AlterationCapability(contract: string, representation: string): boolean { + return contract === 'C1' && representation === C1_ALTERATION_BARS; +} + +const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0; +const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +// The any-alteration bar keeps the red of the event; each alteration takes its own colour. +const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]]; +const color = (i: number) => COLORS[i % COLORS.length]; + +export function c1AlterationFigure(data: IndicadorDatos, selection: FigureSelection): C1AlterationResult { + const unsupported = (reason: string): C1AlterationResult => ({ status: 'unsupported', reason }); + if (!c1AlterationCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada'); + if (data['estrato'] != null) return unsupported('Esta figura no admite una dimensión'); + const periods = selection.periodos ? data.periodos.filter(p => selection.periodos!.includes(p)) : data.periodos; + if (!periods.length) return unsupported('No hay periodos publicados para esta selección'); + const published = data['grupos']; + const groups = Object.entries(published && typeof published === 'object' ? published : {}).filter(([id]) => id !== TOTAL); + if (!groups.length) return unsupported('El indicador no publica grupos por alteración'); + const bars = [{ id: TOTAL, label: ANY_LABEL }, ...groups.map(([id, label]) => ({ id, label: String(label) }))]; + + const cells = periods.map(period => bars.map(bar => + data.filas.filter(r => r['periodo'] === period && r['grupo'] === bar.id && r['estrato'] == null))); + if (cells.some(row => row.some(found => found.length !== 1))) return unsupported('Grupos por alteración incompletos'); + const rows = cells.map(row => row.map(([r]) => r)); + if (rows.some(row => row.some(r => (r['suprimido'] !== 0 && r['suprimido'] !== false) + || !count(r['numerador']) || !count(r['denominador']) || r['numerador'] > r['denominador']))) + return unsupported('Conteos por alteración suprimidos o no verificables'); + + const theme = c2Theme(selection.tema); + const x = bars.map(b => escape(b.label)); + const single = periods.length === 1; + const traces = rows.map((row, p) => { + const y = row.map(r => (r['denominador'] as number) ? 100 * (r['numerador'] as number) / (r['denominador'] as number) : null); + return { type: 'bar', name: periods[p], x, y, + marker: { color: single ? bars.map((_, i) => color(i)) : color(p), line: { color: theme.background, width: 1 } }, + text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false, + customdata: row.map(r => [r['numerador'], r['denominador']]), + hovertemplate: '%{x}' + (single ? '' : ', %{fullData.name}') + '
%{y:.1f} % (%{customdata[0]} de %{customdata[1]} niños)' }; + }); + const figure: PlotlyFigure = { + data: traces, + layout: { autosize: true, height: 400, barmode: 'group', margin: { t: 56, l: 72, r: 24, b: single ? 64 : 96 }, showlegend: !single, + legend: { orientation: 'h', y: -0.3, itemclick: false, itemdoubleclick: false }, + title: { text: escape(String(data['titulo'] ?? data.id)) + (single ? ', ' + periods[0] : '') }, + paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + xaxis: { type: 'category', title: { text: 'Alteración del EEG' }, automargin: true }, + yaxis: { title: { text: '% de niños con EEG de buena calidad' }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } }, + config: { displayModeBar: false }, + }; + const highlight: FigureHighlight = { groups: [], traces: traces.map((_, t) => t), allLabel: 'Todas las alteraciones', + items: bars.map((b, i) => ({ id: b.id, label: b.label, color: single ? color(i) : theme.line, + points: traces.map((_, t) => ({ trace: t, index: i })) })) }; + // Children with a first good EEG over the periods drawn: zero means there is nothing to draw a share of. + const total = rows.reduce((sum, row) => sum + (row[0]['denominador'] as number), 0); + return { status: 'supported', figure, highlight, total, notes: Array.isArray(data.notas) ? [...data.notas] : [] }; +} diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index 00e471a..5d3c484 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -13,6 +13,7 @@ import { periodosDesde, Report, } from './indicadores-fhir'; import * as fx from './indicadores-fhir.fixtures'; +import { c1AlterationFigure } from './indicadores-c1-alteraciones'; import { c2Figure } from './indicadores-c2-adapter'; import { datosValidos } from './indicadores.service'; import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir'; @@ -32,6 +33,29 @@ describe('Indicadores sobre FHIR', () => { expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' }); }); + it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => { + // Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and + // that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures + // hold none for M30). Fails if the groups are dropped or renamed on the way, or the figure stops reading them. + const m30 = measure('M30-resultado-eeg'); + const pop = (code: string, count: number) => ({ code: { coding: [{ code }] }, count }); + const group = (code: string, n: number) => ({ code: { coding: [{ code }] }, population: [pop('denominator', 8), pop('numerator', n)], + measureScore: { value: n / 8 } }); + const codes = (m30.group ?? []).map(g => g.code?.coding?.[0]?.code as string); + const report = { resourceType: 'MeasureReport', id: 'M30-resultado-eeg-1', period: { start: '2025-07-01', end: '2025-12-31' }, + group: codes.map((c, i) => group(c, c === 'TOTAL' ? 4 : i % 3)) } as unknown as Report; + const datos = datosValidos(datosDeReportes(m30, [report], 'semestre'), 'M30_resultado_eeg', 'semestre', ['2025-S2']); + expect(datos.filas.map(f => f['grupo'])).toEqual(codes); + expect(codes).toContain('ritmo_posterior'); + const result = c1AlterationFigure(datos, { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', + tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }); + if (result.status !== 'supported') throw new Error(result.reason); + const [trace] = result.figure.data as Record[]; + expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', + 'Gradiente anteroposterior']); + expect((trace['y'] as number[])[0]).toBe(50); + }); + it('una proporción da numerador, denominador y porcentaje, y por grupo de edad los códigos de la página', () => { // Pins down: the score becomes a percentage, the age groups `16-23`..., and an empty «Sin dato» stratum is left // out. Fails if the fraction isn't multiplied, the codes keep FHIR's underscore or the empty stratum becomes a bar. diff --git a/src/app/features/indicadores/indicadores-figure-labels.spec.ts b/src/app/features/indicadores/indicadores-figure-labels.spec.ts index 1e6db48..c2c0f16 100644 --- a/src/app/features/indicadores/indicadores-figure-labels.spec.ts +++ b/src/app/features/indicadores/indicadores-figure-labels.spec.ts @@ -2,6 +2,7 @@ import { figureDisplayName } from './indicadores-figure-labels'; describe('UX-07A nombres de representaciones', () => { it.each([ + ['fig_c1_barras_alteracion', 'Barras por alteración'], ['fig_c1_grupos', 'Grupos'], ['fig_c1_puntos', 'Puntos'], ['fig_c2_apiladas', 'Barras apiladas'], diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts index 6c77c01..7b19694 100644 --- a/src/app/features/indicadores/indicadores-figure-labels.ts +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -2,6 +2,7 @@ // Exact IDs remain the option values and HTTP identities; never infer a type // from a prefix. Unknown options keep a neutral label in publication order. const FIGURE_LABELS: Readonly> = { + fig_c1_barras_alteracion: 'Barras por alteración', fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad', fig_c1_barras_edad: 'Barras por grupo de edad', fig_c1_dona_edad: 'Dona por grupo de edad', From 4ffd3797b639add3e17554da9b57087481530ff6 Mon Sep 17 00:00:00 2001 From: alberto Date: Fri, 13 Nov 2026 21:15:47 -0600 Subject: [PATCH 27/27] Indicators: the history chart and the KPI card read the total when a measure publishes more groups --- .../indicadores/indicadores-historico-figures.ts | 7 ++++--- .../features/indicadores/indicadores-historico.spec.ts | 10 ++++++++++ src/app/features/indicadores/indicadores-kpi.spec.ts | 8 ++++++++ src/app/features/indicadores/indicadores-kpi.ts | 6 +++--- src/app/features/indicadores/indicadores.models.ts | 8 ++++++++ 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 3b591ce..5149db6 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -1,4 +1,4 @@ -import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette'; import { sortedPeriods } from './indicadores-periodos'; import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi'; @@ -67,8 +67,9 @@ function banda(periodos: string[], bajo: (number | null)[], alto: (number | null } // Separate rows from what is missing or suppressed; a period is judged by its only row. function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record) => boolean) { - const filas = new Map(data.filas.map(row => [row['periodo'] as string, row])); - if (filas.size !== data.filas.length) throw new Error('Filas ambiguas'); + const delTotal = filasDelGrupo(data, 'TOTAL'); + const filas = new Map(delTotal.map(row => [row['periodo'] as string, row])); + if (filas.size !== delTotal.length) throw new Error('Filas ambiguas'); const suprimidos: string[] = [], sinDato: string[] = []; const validas = periodos.map(periodo => { const row = filas.get(periodo); diff --git a/src/app/features/indicadores/indicadores-historico.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts index 3d46ec8..3f5b67e 100644 --- a/src/app/features/indicadores/indicadores-historico.spec.ts +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -36,6 +36,16 @@ describe('Figuras de histórico', () => { expect(suprimidos).toEqual(['feb 2024']); expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]); }); + it('C1 con grupos adicionales dibuja la línea del total', () => { + // Pins down: a measure that publishes one group per alteration next to its total (TEA's EEG result) gets its + // history from the total's row of each period. Fails if the other groups' rows count as a second row of the + // period («Filas ambiguas»), or if two rows of the total stop being refused. + const grupos = { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior' }; + const filas = base.periodos.flatMap(p => [{ ...c1(p, 40), grupo: 'TOTAL' }, { ...c1(p, 10), grupo: 'ritmo_posterior' }]); + const data: IndicadorDatos = { ...base, contrato: 'C1', grupos, filas }; + expect(traza(data, 1).y).toEqual([40, 40, 40]); + expect(() => historicoFigura({ ...data, filas: [...filas, { ...c1('2024-01', 5), grupo: 'TOTAL' }] }, 'claro')).toThrow('Filas ambiguas'); + }); it('C1 es una línea que no cruza huecos y su banda tampoco', () => { const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] }; const { suprimidos, figure } = historicoFigura(data, 'claro'); diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index 801932f..bb7fa56 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -21,6 +21,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => { expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6'); expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0'); }); + it('C1 con grupos adicionales publicados lee la fila de su grupo', () => { + // Pins down: the rows of the other groups a measure publishes (one per alteration) don't make the card + // unconsolidable; a row of a group nobody published still does. Fails if those rows are mixed into the total. + const rows = [{ ...total, grupo: c1Group, valor: 50, numerador: 3, denominador: 6 }, { ...total, grupo: 'ritmo_posterior', valor: 10, numerador: 1, denominador: 6 }]; + const d = { ...data(domain, 1, rows), grupos: { [c1Group]: 'Total', ritmo_posterior: 'Ritmo posterior' } }; + expect(kpiResult(d, definitions[domain][1], domain, applied).value).toBe('50.0'); + expect(kpiResult({ ...d, grupos: { [c1Group]: 'Total' } }, definitions[domain][1], domain, applied).state).toBe('Selección no consolidable'); + }); it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => { const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]); expect(result.value).toBe(0); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 64d47f4..5c05fcc 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -1,4 +1,4 @@ -import { Dominio, IndicadorDatos } from './indicadores.models'; +import { Dominio, filasDelGrupo, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; import { percentNumber } from './indicadores-format'; @@ -72,9 +72,9 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped; const period = data.periodos[0]; if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped; - const rows = data.filas; - if (!rows.length) return { state: 'Sin filas utilizables' }; const group = definition.contrato === 'C1' ? C1_GROUP[domain] : 'TOTAL'; + const rows = definition.contrato === 'C1' ? filasDelGrupo(data, group) : data.filas; + if (!rows.length) return { state: 'Sin filas utilizables' }; if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped; if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped; if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' }; diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index b8980a0..c1613e5 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -63,6 +63,14 @@ export interface PlotlyFigure { export type Tema = 'claro' | 'oscuro'; export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; indicador: string; figura: string; tema: Tema; periodos?: string[]; } +// A measure may publish more groups next to `group` (TEA's EEG result: one per alteration). The rows without those +// of the other published groups; a row of a group nobody published stays, for the caller to refuse. +export function filasDelGrupo(data: IndicadorDatos, group: string): Record[] { + const published = data['grupos']; + const others = new Set(Object.keys(published && typeof published === 'object' ? published : {}).filter(id => id !== group)); + return others.size ? data.filas.filter(row => !others.has(row['grupo'] as string)) : data.filas; +} + export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null { if (tipo !== 'semestre' && tipo !== 'mes') return null; const parts = value.split(',').map(part => part.trim());