feat(tea): seguimiento con resumen por paciente y resumen por periodo
- 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/<id>). - 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.
This commit is contained in:
@@ -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.');
|
||||
|
||||
@@ -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'));
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.' });
|
||||
|
||||
@@ -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<Dominio, KpiDefinition[]> = {
|
||||
{ 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']) };
|
||||
|
||||
@@ -76,8 +76,11 @@
|
||||
@let kpis = opportunityKpis;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||
@let resumen = teaResumenPeriodo;
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||
@for (definition of kpis; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
|
||||
@@ -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); }
|
||||
|
||||
@@ -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<readonly IndicadorNavegacionItem[]>(() =>
|
||||
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<Element, IndicadorCatalogCard>();
|
||||
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;
|
||||
|
||||
@@ -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<HTMLElement>('#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);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
@if (dominio !== 'cacu') {
|
||||
@if (dominio !== 'cacu' && dominio !== 'tea') {
|
||||
<p>El seguimiento aún no está disponible.</p>
|
||||
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
@@ -19,8 +19,8 @@
|
||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||
</select></label>
|
||||
<label>Estatus de seguimiento <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
|
||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||
</select></label>
|
||||
<label>Ordenar por prioridad <select name="prioridad" disabled>
|
||||
@@ -33,8 +33,30 @@
|
||||
@if (status === 'pending') { <p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p> }
|
||||
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
|
||||
@if (status === 'error' || status === 'pending') { <button type="button" (click)="retry()">Reintentar seguimiento</button> }
|
||||
@if (data; as response) {
|
||||
@if (response; as response) {
|
||||
<p>Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.</p>
|
||||
}
|
||||
@if (teaData; as response) {
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Alteraciones EEG</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<td><button class="row-toggle" type="button" [attr.aria-expanded]="teaAbierto === item.id_seudonimo" [attr.aria-controls]="'tea-detalle-' + item.id_seudonimo"
|
||||
[attr.aria-label]="(teaAbierto === item.id_seudonimo ? 'Ocultar' : 'Ver') + ' resumen del paciente ' + item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<span class="chevron" aria-hidden="true"></span>{{ item.id_seudonimo }}</button></td><td>{{ item.grupo_edad }}</td><td>{{ item.ultimo_eeg ?? 'No disponible' }}</td>
|
||||
<td>{{ item.mchat ?? 'No disponible' }}</td><td>{{ item.css_ados2 ?? 'No disponible' }}</td>
|
||||
<td>@if (item.alteraciones_eeg; as eeg) { <span class="eeg" [class.eeg-anormal]="eeg === 'anormal'">{{ eeg === 'anormal' ? 'Anormal' : 'Normal' }}</span> } @else { No disponible }</td></tr>
|
||||
@if (teaAbierto === item.id_seudonimo) {
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="6"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
|
||||
}
|
||||
} @empty { <tr><td colspan="6">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else if (data; as response) {
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
@@ -51,6 +73,8 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
@if (response; as response) {
|
||||
<nav aria-label="Paginación de seguimiento">
|
||||
<button type="button" [disabled]="response.paginacion.page <= 1" (click)="navigate(response.paginacion.page - 1)">Anterior</button>
|
||||
<span>Página {{ response.paginacion.page }} de {{ response.paginacion.total_pages }}, {{ response.paginacion.total_items }} registros</span>
|
||||
|
||||
@@ -21,3 +21,13 @@ tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issst
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
|
||||
tbody tr.tea-row { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
.row-toggle { display: inline-flex; align-items: center; gap: .5rem; min-height: 44px; padding: .35rem .5rem; border: 0; background: transparent;
|
||||
color: var(--issste-text); font: inherit; font-weight: 600; text-align: left; cursor: pointer; }
|
||||
.chevron { width: .5rem; height: .5rem; border-right: 2px solid currentColor; border-bottom: 2px solid currentColor; transform: rotate(-45deg); transition: transform 150ms ease; }
|
||||
.row-toggle[aria-expanded=true] .chevron { transform: rotate(45deg); }
|
||||
@media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } }
|
||||
tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); }
|
||||
|
||||
@@ -10,10 +10,12 @@ import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent],
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen],
|
||||
providers: [PacienteDetalleState],
|
||||
templateUrl: './indicadores-tracking.html',
|
||||
styleUrl: './indicadores-tracking.scss',
|
||||
@@ -24,6 +26,7 @@ export class IndicadoresTracking implements OnChanges {
|
||||
@Input() active = false;
|
||||
private readonly service = inject(CacuSeguimientoService);
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly teaService = inject(TeaSeguimientoService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly injector = inject(Injector);
|
||||
@@ -31,11 +34,15 @@ export class IndicadoresTracking implements OnChanges {
|
||||
readonly fichaPacienteAbierta = output<boolean>();
|
||||
private controlPaciente?: HTMLElement;
|
||||
private readonly requests = new Subject<SeguimientoQuery | null>();
|
||||
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
|
||||
private initialized = false;
|
||||
private previousDomain?: Dominio;
|
||||
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
||||
message = '';
|
||||
data?: SeguimientoResponse;
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
@@ -43,12 +50,13 @@ export class IndicadoresTracking implements OnChanges {
|
||||
private applied: SeguimientoQuery = { ...this.draft };
|
||||
readonly latestStudy = latestStudy;
|
||||
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
|
||||
get response() { return this.dominio === 'tea' ? this.teaData : this.data; }
|
||||
constructor() {
|
||||
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
|
||||
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
|
||||
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' });
|
||||
this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe(
|
||||
map(data => ({ data, message: '', status: 'ready' as const })),
|
||||
catchError(error => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
|
||||
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
|
||||
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' }))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||
if (!result) return;
|
||||
this.changeDetector.markForCheck();
|
||||
this.status = result.status; this.data = result.data; this.message = result.message;
|
||||
@@ -66,25 +74,38 @@ export class IndicadoresTracking implements OnChanges {
|
||||
}
|
||||
}
|
||||
});
|
||||
this.teaRequests.pipe(switchMap(q => q ? defer(() => this.teaService.consultar(q)).pipe(
|
||||
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||
if (!result) return;
|
||||
this.changeDetector.markForCheck();
|
||||
this.status = result.status; this.teaData = result.data; this.message = result.message; this.teaAbierto = undefined;
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.draft = { ...this.applied };
|
||||
}
|
||||
});
|
||||
}
|
||||
ngOnChanges() {
|
||||
if (this.previousDomain !== this.dominio) {
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.data = undefined;
|
||||
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
}
|
||||
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
||||
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
|
||||
}
|
||||
private load(q: SeguimientoQuery) {
|
||||
if (this.dominio !== 'cacu') return;
|
||||
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
|
||||
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.applied = { ...q }; this.requests.next(q);
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() { this.load({ ...this.draft, page: 1 }); }
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return;
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
this.load({ ...this.applied, page });
|
||||
}
|
||||
abrirPaciente(paciente: SeguimientoPaciente, evento: Event) {
|
||||
@@ -100,6 +121,12 @@ export class IndicadoresTracking implements OnChanges {
|
||||
this.pacienteDetalle.abrir(paciente, this.data.corte);
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
alternarTea(id: string, evento: Event) {
|
||||
evento.stopPropagation();
|
||||
// Row clicks that land on a control are left to that control.
|
||||
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||
this.teaAbierto = this.teaAbierto === id ? undefined : id;
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
|
||||
@@ -137,6 +137,8 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
const before = cards(), panel = panels()[0], result = panel.result();
|
||||
for (const section of ['seguimiento', 'datos'] as const) {
|
||||
page.changeSection(section); await render();
|
||||
// TEA's Seguimiento loads its patient list; that request is unrelated to the cards.
|
||||
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||
// Even stale geometry/observer notifications cannot activate hidden cards.
|
||||
positions(cards().map(() => [200, 0])); notify(1); await idle();
|
||||
expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true);
|
||||
@@ -233,6 +235,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
|
||||
for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
|
||||
page.changeSection(section); await idle();
|
||||
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
|
||||
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
|
||||
expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true);
|
||||
}
|
||||
|
||||
@@ -284,6 +284,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
expect(root.querySelector('app-paciente-detalle')).toBeNull();
|
||||
expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado');
|
||||
expect(root.querySelector('tbody button')).toBeNull();
|
||||
// TEA loads its own list, which has no patient-detail buttons.
|
||||
http.expectOne(r => r.url === '/tea/seguimiento');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
@if (status() === 'loading') { <p role="status">Cargando resumen del paciente…</p> }
|
||||
@if (status() === 'error') {
|
||||
<p role="alert">No se pudo cargar el resumen del paciente.</p>
|
||||
<button type="button" (click)="load()">Reintentar resumen</button>
|
||||
}
|
||||
@if (status() === 'ready' && detalle(); as d) {
|
||||
<div class="resumen">
|
||||
<section class="panel" aria-label="Resumen ADOS-2">
|
||||
<h3>ADOS-2</h3>
|
||||
@if (d.ados2; as a) {
|
||||
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
|
||||
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
</div>
|
||||
@for (dom of a.dominios; track dom.codigo) {
|
||||
<div class="dominio">
|
||||
<span>{{ dom.etiqueta }} ({{ dom.codigo }})</span><span>{{ dom.puntaje }} / {{ dom.maximo }}</span>
|
||||
<span class="bar" aria-hidden="true"><span [style.width.%]="pct(dom.puntaje, dom.maximo)"></span></span>
|
||||
</div>
|
||||
}
|
||||
<details open>
|
||||
<summary>Puntajes por reactivo</summary>
|
||||
<table class="reactivos">
|
||||
<thead><tr><th scope="col">Reactivo</th><th scope="col">Puntaje</th><th scope="col">Algoritmo</th></tr></thead>
|
||||
@for (dom of a.dominios; track dom.codigo) {
|
||||
<tbody>
|
||||
<tr><th scope="rowgroup" colspan="3">{{ dom.etiqueta }}</th></tr>
|
||||
@for (r of dom.reactivos; track r.codigo) {
|
||||
<tr><td>{{ r.codigo }} · {{ r.etiqueta }}</td><td>{{ r.puntaje }}</td><td>{{ r.puntaje_algoritmo }}</td></tr>
|
||||
}
|
||||
</tbody>
|
||||
}
|
||||
</table>
|
||||
</details>
|
||||
} @else { <p>Sin evaluación ADOS-2 registrada.</p> }
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-label="Calidad del EEG">
|
||||
<h3>Calidad del EEG</h3>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-calidad]="e.calidad">{{ e.puntaje_calidad }}<small>de 100</small></span>
|
||||
<span><strong>{{ calidad[e.calidad] }}</strong><small>Segmentos útiles: {{ e.segmentos_utiles_pct }} %</small></span>
|
||||
</div>
|
||||
<dl>
|
||||
<dt>Canales rechazados</dt><dd>{{ e.canales_rechazados }} de {{ e.canales }}</dd>
|
||||
<dt>Impedancia máxima</dt><dd>{{ e.impedancia_max_kohm }} kΩ</dd>
|
||||
<dt>Artefactos de parpadeo</dt><dd>{{ e.artefactos_pct.parpadeo }} %</dd>
|
||||
<dt>Artefactos de movimiento</dt><dd>{{ e.artefactos_pct.movimiento }} %</dd>
|
||||
<dt>Artefactos musculares</dt><dd>{{ e.artefactos_pct.muscular }} %</dd>
|
||||
</dl>
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<section class="panel mapa" aria-label="Mapa de zonas afectadas">
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ e.mapa.metrica }} · mapa ilustrativo</p>
|
||||
@if (figura) {
|
||||
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'320px'"
|
||||
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
|
||||
@for (r of e.regiones; track r.codigo) {
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
:host { display: block; }
|
||||
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(18rem, 1fr)); gap: 1rem; }
|
||||
.panel { min-width: 0; padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); }
|
||||
h3 { margin: 0 0 .25rem; font-size: 1.1rem; }
|
||||
.meta { margin: 0 0 1rem; font-size: .875rem; color: var(--issste-text-secondary); }
|
||||
.headline { display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem; }
|
||||
.headline small { display: block; margin-top: .25rem; color: var(--issste-text-secondary); }
|
||||
.css { display: inline-flex; flex-direction: column; align-items: center; justify-content: center; min-width: 4.5rem; padding: .5rem;
|
||||
border: 2px solid var(--issste-border); border-radius: var(--issste-radius); font-size: 1.25rem; font-weight: 700; }
|
||||
.css small { margin: 0; font-size: .7rem; font-weight: 400; }
|
||||
.css[data-nivel=alto], .css[data-calidad=deficiente] { border-color: #B3261E; color: #B3261E; }
|
||||
.css[data-nivel=moderado], .css[data-calidad=aceptable] { border-color: #B26A00; color: #B26A00; }
|
||||
.css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=buena] { border-color: var(--issste-accent); }
|
||||
.dominio { display: grid; grid-template-columns: 1fr auto; gap: .25rem 1rem; margin-bottom: .75rem; font-size: .9rem; }
|
||||
.bar { grid-column: 1 / -1; height: .5rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; }
|
||||
.bar span { display: block; height: 100%; background: var(--issste-text); }
|
||||
details { margin-top: 1rem; }
|
||||
summary { cursor: pointer; font-weight: 600; min-height: 44px; display: flex; align-items: center; }
|
||||
.reactivos { width: 100%; min-width: 0; font-size: .85rem; border-collapse: collapse; }
|
||||
.reactivos th, .reactivos td { padding: .4rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; }
|
||||
.reactivos td:not(:first-child), .reactivos thead th:not(:first-child) { text-align: end; white-space: nowrap; }
|
||||
.reactivos tbody th { background: var(--issste-background); }
|
||||
dl { display: grid; grid-template-columns: 1fr auto; gap: .5rem 1rem; margin: 0; font-size: .9rem; }
|
||||
dt { color: var(--issste-text-secondary); } dd { margin: 0; text-align: end; font-weight: 600; }
|
||||
.regiones { margin: .5rem 0 0; padding-inline-start: 1.25rem; font-size: .9rem; }
|
||||
.regiones li { padding: .2rem 0; }
|
||||
.regiones li span:last-child { float: inline-end; font-variant-numeric: tabular-nums; }
|
||||
.regiones .destacada { font-weight: 700; }
|
||||
button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; }
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Component, DestroyRef, 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, TeaEeg, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
|
||||
const CLASIFICACION: Record<TeaAdos2['clasificacion'], string> = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' };
|
||||
// ADOS-2 calibrated severity score ranges.
|
||||
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
|
||||
const CALIDAD: Record<TeaEeg['calidad'], string> = { buena: 'Buena', aceptable: 'Aceptable', deficiente: 'Deficiente' };
|
||||
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 } },
|
||||
{ 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;
|
||||
return {
|
||||
data: [
|
||||
{ type: 'contour', x: m.x, y: m.y, z: m.z, zmin: -3, zmax: 3, zmid: 0, colorscale: 'RdBu', connectgaps: false,
|
||||
contours: { coloring: 'heatmap', showlines: true }, line: { width: .5, color: 'rgba(8,24,57,.3)' },
|
||||
colorbar: { title: { text: 'z', side: 'top' }, thickness: 12, len: .8 }, hovertemplate: 'z = %{z:.2f}<extra></extra>' },
|
||||
{ type: 'scatter', mode: 'markers+text', x: m.electrodos.map(e => e.x), y: m.electrodos.map(e => e.y), text: m.electrodos.map(e => e.nombre),
|
||||
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,
|
||||
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 },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-tea-paciente-resumen',
|
||||
imports: [PlotlyChart],
|
||||
templateUrl: './tea-paciente-resumen.html',
|
||||
styleUrl: './tea-paciente-resumen.scss',
|
||||
})
|
||||
export class TeaPacienteResumen implements OnInit {
|
||||
@Input({ required: true }) id = '';
|
||||
private readonly service = inject(TeaSeguimientoService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
|
||||
figura?: PlotlyFigure;
|
||||
readonly clasificacion = CLASIFICACION;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
ngOnInit() { this.load(); }
|
||||
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'); },
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { signal } from '@angular/core';
|
||||
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 };
|
||||
function panel(id: string, result: Result) {
|
||||
return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType<typeof signal<Result>>; retry: ReturnType<typeof vi.fn> };
|
||||
}
|
||||
const listo = (value: string | number, period = '2025-S2'): Result => ({ state: 'Disponible', value, period });
|
||||
|
||||
describe('Resumen TEA por periodo', () => {
|
||||
function render(paneles: IndicadorKpiPanel[]) {
|
||||
const fixture = TestBed.createComponent(TeaResumenPeriodo);
|
||||
fixture.componentRef.setInput('periodo', '2025-S2'); fixture.componentRef.setInput('paneles', paneles);
|
||||
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'))];
|
||||
|
||||
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('Para el periodo 2025-S2, se evaluaron 409 pacientes.');
|
||||
expect(text).toContain('De los pacientes con nota médica, 86.5 % tuvo diagnóstico de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('hasta el diagnóstico fue 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 %']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
const paneles = completos();
|
||||
paneles[1].result.set({ state: 'Dato oculto por tamaño' });
|
||||
paneles[2].result.set(listo(30, '2025-S1'));
|
||||
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M22_diagnosticados_sin_eeg')).nativeElement;
|
||||
const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato'));
|
||||
expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']);
|
||||
expect(root.textContent).not.toContain('30 días');
|
||||
});
|
||||
|
||||
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||
const paneles = completos();
|
||||
paneles[0].result.set({ state: 'Cargando…', loading: true });
|
||||
paneles[3].result.set({ state: 'Error de consulta' });
|
||||
const fixture = render(paneles);
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('article')!.getAttribute('aria-busy')).toBe('true');
|
||||
root.querySelector<HTMLButtonElement>('button')!.click();
|
||||
expect(paneles[3].retry).toHaveBeenCalledOnce();
|
||||
expect(paneles[0].retry).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
|
||||
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
|
||||
|
||||
// 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.
|
||||
@Component({
|
||||
selector: 'app-tea-resumen-periodo',
|
||||
imports: [MatButtonModule, NgTemplateOutlet],
|
||||
template: `
|
||||
<article class="resumen" [attr.aria-busy]="cargando">
|
||||
<p>
|
||||
Para el periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M23_pacientes_evaluados', '') }" />
|
||||
pacientes. De los pacientes con nota médica, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
|
||||
tuvo diagnóstico de TEA (CIE-10 F84.0). La mediana del tiempo desde la aplicación del M-CHAT por psicología hasta el diagnóstico fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M21_diagnosticados_con_eeg', ' %') }" />
|
||||
tenían EEG y <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M22_diagnosticados_sin_eeg', ' %') }" /> no lo tenían.
|
||||
</p>
|
||||
@if (conError.length) {
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||
}
|
||||
</article>
|
||||
<ng-template #dato let-v>
|
||||
<span class="dato" [class.listo]="v.estado === 'listo'" [class.sin-dato]="v.estado === 'sin_dato'" [attr.title]="v.detalle ?? null">{{ v.texto }}@if (v.detalle) {<span class="visually-hidden"> ({{ v.detalle }})</span>}</span>
|
||||
</ng-template>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
.resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; }
|
||||
.dato { display: inline-block; padding: 0 .5em; border-radius: var(--issste-radius); line-height: 1.6; font-weight: 700; white-space: nowrap;
|
||||
background: var(--issste-background); border: 1px dashed var(--issste-border); color: var(--issste-text-secondary); }
|
||||
.dato.listo { background: color-mix(in srgb, var(--issste-accent) 22%, var(--issste-surface)); border: 1px solid var(--issste-accent); color: var(--issste-text); }
|
||||
.dato.sin-dato { font-weight: 400; font-style: italic; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
button { margin-top: var(--issste-space-4); }
|
||||
`,
|
||||
})
|
||||
export class TeaResumenPeriodo {
|
||||
@Input({ required: true }) periodo!: string;
|
||||
@Input({ required: true }) paneles: readonly IndicadorKpiPanel[] = [];
|
||||
// Panels render after this paragraph, so on their first pass their inputs are not set yet.
|
||||
private panel(id: string) { return this.paneles.find(p => p.definition?.id === id); }
|
||||
valor(id: string, sufijo: string): Valor {
|
||||
const result = this.panel(id)?.result();
|
||||
if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' };
|
||||
if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' };
|
||||
// Never show a value from another period in a sentence about this one.
|
||||
if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo)
|
||||
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
|
||||
return { texto: result.value + sufijo, 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()); }
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
|
||||
export type AlteracionesEeg = 'normal' | 'anormal';
|
||||
export interface TeaSeguimientoPaciente {
|
||||
id_seudonimo: string;
|
||||
grupo_edad: string;
|
||||
ultimo_eeg: string | null;
|
||||
mchat: number | null;
|
||||
css_ados2: number | null;
|
||||
alteraciones_eeg: AlteracionesEeg | null;
|
||||
}
|
||||
export interface TeaSeguimientoResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
|
||||
filtros: { alteraciones_eeg: AlteracionesEeg | null };
|
||||
items: TeaSeguimientoPaciente[];
|
||||
}
|
||||
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[] }
|
||||
export interface TeaAdos2 {
|
||||
fecha: string; modulo: string; algoritmo: string; dominios: TeaAdosDominio[]; total: number; total_maximo: number;
|
||||
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
}
|
||||
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||||
export interface TeaEeg {
|
||||
fecha: string; duracion_min: number; canales: number; canales_rechazados: number; segmentos_utiles_pct: number; impedancia_max_kohm: number;
|
||||
artefactos_pct: { parpadeo: number; movimiento: number; muscular: number }; puntaje_calidad: number; calidad: 'buena' | 'aceptable' | 'deficiente';
|
||||
regiones: TeaEegRegion[];
|
||||
mapa: { metrica: string; x: number[]; y: number[]; z: (number | null)[][]; 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 ALTERACIONES_EEG: SeguimientoStatus[] = [{ codigo: 'normal', etiqueta: 'Normal' }, { codigo: 'anormal', etiqueta: 'Anormal' }];
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal';
|
||||
const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
|
||||
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.');
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
// M-CHAT-R/F totals range 0–20; ADOS-2 calibrated severity scores range 1–10.
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || !eeg(filters['alteraciones_eeg'])
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => record(item)
|
||||
&& typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string'
|
||||
&& (item['ultimo_eeg'] === null || isoDate(item['ultimo_eeg']))
|
||||
&& score(item['mchat'], 0, 20) && score(item['css_ados2'], 1, 10)
|
||||
&& eeg(item['alteraciones_eeg'])))
|
||||
throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as TeaSeguimientoResponse;
|
||||
}
|
||||
|
||||
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||
const pct = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 100;
|
||||
const text = (v: unknown) => typeof v === 'string' && v.length > 0;
|
||||
function validAdos(a: unknown): boolean {
|
||||
if (a === null) return true;
|
||||
if (!record(a) || !isoDate(a['fecha']) || !text(a['modulo']) || !text(a['algoritmo']) || !score(a['css'], 1, 10)
|
||||
|| !['autismo', 'espectro_autista', 'no_espectro'].includes(a['clasificacion'] as string)
|
||||
|| !['minimo', 'bajo', 'moderado', 'alto'].includes(a['nivel_css'] as string) || !Array.isArray(a['dominios'])) return false;
|
||||
// Items score 0–3 (algorithm 0–2); each domain and the total must be the sum of their parts.
|
||||
const dominios = a['dominios'] as unknown[];
|
||||
const ok = dominios.every(d => record(d) && text(d['codigo']) && text(d['etiqueta']) && Array.isArray(d['reactivos'])
|
||||
&& d['reactivos'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && score(r['puntaje'], 0, 3) && score(r['puntaje_algoritmo'], 0, 2))
|
||||
&& d['puntaje'] === (d['reactivos'] as TeaAdosReactivo[]).reduce((t, r) => t + r.puntaje_algoritmo, 0)
|
||||
&& d['maximo'] === 2 * (d['reactivos'] as unknown[]).length);
|
||||
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||||
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||||
}
|
||||
function validEeg(e: unknown): boolean {
|
||||
if (e === null) return true;
|
||||
if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !integer(e['canales_rechazados'])
|
||||
|| (e['canales_rechazados'] as number) > (e['canales'] as number) || !pct(e['segmentos_utiles_pct']) || !finite(e['impedancia_max_kohm'])
|
||||
|| !pct(e['puntaje_calidad']) || !['buena', 'aceptable', 'deficiente'].includes(e['calidad'] as string)) return false;
|
||||
const art = e['artefactos_pct'], mapa = e['mapa'];
|
||||
if (!record(art) || !['parpadeo', 'movimiento', 'muscular'].every(k => pct(art[k]))) return false;
|
||||
if (!Array.isArray(e['regiones']) || !e['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))) 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']));
|
||||
}
|
||||
export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']))
|
||||
throw new Error('Resumen del paciente inválido');
|
||||
return v as unknown as TeaPacienteDetalle;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class TeaSeguimientoService {
|
||||
private readonly http = inject(HttpClient);
|
||||
// `estatus` carries the EEG filter so the shared form and query work for both domains.
|
||||
consultar(query: SeguimientoQuery) {
|
||||
if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos');
|
||||
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
|
||||
if (query.corte) params = params.set('corte', query.corte);
|
||||
if (query.estatus) params = params.set('alteraciones_eeg', query.estatus);
|
||||
return this.http.get<unknown>('/tea/seguimiento', { params }).pipe(map(teaSeguimientoResponse));
|
||||
}
|
||||
detalle(id: string) {
|
||||
return this.http.get<unknown>(`/tea/seguimiento/${encodeURIComponent(id)}`).pipe(map(v => teaPacienteDetalle(v, id)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
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 { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
|
||||
const item = { id_seudonimo: 'T-0001', grupo_edad: '18-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal' };
|
||||
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 }],
|
||||
};
|
||||
const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) });
|
||||
const detalle = {
|
||||
simulado: true, id_seudonimo: 'T-0001', grupo_edad: '18-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',
|
||||
dominios: [{ codigo: 'AS', etiqueta: 'Afecto social', puntaje: 4, maximo: 4, reactivos: [reactivo('A2', 3), reactivo('B1', 2)] },
|
||||
{ codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] },
|
||||
eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, canales_rechazados: 1, segmentos_utiles_pct: 82, impedancia_max_kohm: 12,
|
||||
artefactos_pct: { parpadeo: 5, movimiento: 10, muscular: 3 }, puntaje_calidad: 78, calidad: 'buena',
|
||||
regiones: [{ codigo: 'central', etiqueta: 'Central', valor_z: 2.1 }],
|
||||
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 }] } },
|
||||
};
|
||||
const anormal = { ...data, filtros: { alteraciones_eeg: 'anormal' }, paginacion: { ...data.paginacion, total_items: 1 }, items: [item] };
|
||||
|
||||
describe('Seguimiento TEA', () => {
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
const runtime = { react: vi.fn().mockResolvedValue(undefined), purge: vi.fn(), Plots: { resize: vi.fn().mockResolvedValue(undefined) } };
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
function open() {
|
||||
const fixture = TestBed.createComponent(IndicadoresTracking);
|
||||
fixture.componentRef.setInput('domainLabel', 'TEA'); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('active', true);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
const request = () => http.expectOne(r => r.url === '/tea/seguimiento');
|
||||
it('muestra las seis 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']);
|
||||
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(root.textContent).toContain('Página 1 de 1, 2 registros');
|
||||
http.verify();
|
||||
});
|
||||
it('usa los filtros de CaCu con Alteraciones EEG en lugar del estatus', () => {
|
||||
const fixture = open();
|
||||
const first = request();
|
||||
expect(first.request.params.get('meses')).toBe('3');
|
||||
expect(first.request.params.has('alteraciones_eeg')).toBe(false);
|
||||
first.flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('input[type=date]')).not.toBeNull();
|
||||
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
|
||||
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
|
||||
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal']);
|
||||
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
|
||||
fixture.componentInstance.apply();
|
||||
const filtered = request();
|
||||
expect(filtered.request.params.get('alteraciones_eeg')).toBe('anormal');
|
||||
expect(filtered.request.params.get('corte')).toBe('2026-08-31');
|
||||
expect(filtered.request.params.get('meses')).toBe('6');
|
||||
expect(filtered.request.params.get('page_size')).toBe('20');
|
||||
expect(filtered.request.params.get('page')).toBe('1');
|
||||
filtered.flush(anormal); fixture.detectChanges();
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(1);
|
||||
expect(fixture.componentInstance.draft.estatus).toBe('anormal');
|
||||
http.verify();
|
||||
});
|
||||
it('rechaza datos reales, puntajes fuera de rango y más filas que el tamaño de página', () => {
|
||||
expect(() => teaSeguimientoResponse(data)).not.toThrow();
|
||||
expect(() => teaSeguimientoResponse({ ...data, simulado: false })).toThrow();
|
||||
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, mchat: 21 }] })).toThrow();
|
||||
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, css_ados2: 0 }] })).toThrow();
|
||||
expect(() => teaSeguimientoResponse({ ...data, items: [{ ...item, alteraciones_eeg: 'dudoso' }] })).toThrow();
|
||||
expect(() => teaSeguimientoResponse({ ...data, filtros: { alteraciones_eeg: 'dudoso' } })).toThrow();
|
||||
expect(() => teaSeguimientoResponse({ ...data, paginacion: { ...data.paginacion, page_size: 1 } })).toThrow();
|
||||
const fixture = open();
|
||||
request().flush({ ...data, simulado: false }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo consultar');
|
||||
});
|
||||
it('despliega un resumen por fila, uno a la vez, y lo pide al abrirlo', () => {
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const toggles = root.querySelectorAll<HTMLButtonElement>('button.row-toggle');
|
||||
expect(toggles).toHaveLength(2);
|
||||
expect(toggles[0].getAttribute('aria-expanded')).toBe('false');
|
||||
toggles[0].click(); fixture.detectChanges();
|
||||
expect(toggles[0].getAttribute('aria-expanded')).toBe('true');
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
const panel = root.querySelector('#tea-detalle-T-0001')!;
|
||||
expect(panel.textContent).toContain('CSS 3');
|
||||
expect(panel.textContent).toContain('Afecto social (AS)');
|
||||
expect(panel.textContent).toContain('Buena');
|
||||
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
(root.querySelectorAll('tbody tr.tea-row')[1] as HTMLElement).click(); fixture.detectChanges();
|
||||
expect(root.querySelector('#tea-detalle-T-0001')).toBeNull();
|
||||
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002', ados2: null, eeg: null }); fixture.detectChanges();
|
||||
expect(root.querySelector('#tea-detalle-T-0002')?.textContent).toContain('Sin evaluación ADOS-2 registrada.');
|
||||
toggles[1].click(); fixture.detectChanges();
|
||||
expect(root.querySelector('tr.tea-detalle')).toBeNull();
|
||||
http.verify();
|
||||
});
|
||||
it('muestra un error recuperable si el resumen no es válido', () => {
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, id_seudonimo: 'T-0099' }); fixture.detectChanges();
|
||||
expect(root.querySelector('#tea-detalle-T-0001')?.textContent).toContain('No se pudo cargar el resumen del paciente.');
|
||||
http.verify();
|
||||
});
|
||||
it('valida que los puntajes ADOS-2 sumen y que el mapa sea rectangular', () => {
|
||||
expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, simulado: false }, 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, total: 6 } }, 'T-0001')).toThrow();
|
||||
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, calidad: 'regular' } }, 'T-0001')).toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user