feat(tea): intervalo de análisis, resumen más preciso y alteraciones del EEG
- Filtro general: «Intervalo de análisis» (Semestral/Mensual) en lugar de «Modalidad»; al cambiar de intervalo se elige el periodo más reciente. - Resumen de TEA: evaluaciones con o sin diagnóstico y diagnóstico positivo de TEA explícito. - Seguimiento: panel «Alteraciones del EEG» (exponente aperiódico, husos del sueño, entropía multiescala) con posibles efectos asociados. Datos de ejemplo, pendientes de validación médica. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -215,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(JSON.stringify(page.result().figure)).toBe(original);
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
});
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
@@ -234,12 +234,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
manual.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => {
|
||||
load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 };
|
||||
@@ -300,7 +295,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
const control = filters(); control.select([]);
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
@@ -310,7 +305,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
const control = filters(); control.select([]); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
apply();
|
||||
const req = figure();
|
||||
@@ -332,7 +327,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
@@ -347,7 +342,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
});
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
apply(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
@@ -361,7 +356,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
|
||||
it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
|
||||
@@ -87,7 +87,7 @@ describe('KPI integración con autoridad global', () => {
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
editor.select([]); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
|
||||
@@ -1,45 +1,31 @@
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de tiempo</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodo' }}</span></mat-select-trigger>
|
||||
<mat-option value="todos">Todos con reporte</mat-option>
|
||||
<mat-option value="manual">Elegir periodo</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (entry.draft.mode !== 'todos') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
||||
@for (period of options; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
@if (availability) {
|
||||
@for (period of unavailableSelection; track period) { <mat-option [value]="period" disabled>{{ period }}, disponibilidad no confirmada</mat-option> }
|
||||
}
|
||||
</mat-select>
|
||||
<mat-hint>{{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }}</mat-hint>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
@if (availability) {
|
||||
@if (availability.status === 'loading') { <p role="status">Consultando periodos disponibles…</p> }
|
||||
@else if (availability.status === 'error') {
|
||||
<p role="alert">No se pudo completar la consulta de periodos disponibles.</p>
|
||||
<button type="button" mat-stroked-button (click)="retryAvailability.emit()">Reintentar disponibilidad</button>
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de tiempo.</p> }
|
||||
} @else if (!options.length) { <p role="status">Sin reportes disponibles para este intervalo de análisis.</p> }
|
||||
@if (entry.draft.mode === 'explicit' && unavailableSelection.length) { <p role="status">La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.</p> }
|
||||
}
|
||||
@if (!availability && entry.draft.mode !== 'todos') {
|
||||
@if (!availability) {
|
||||
<p class="filter-help">Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields period-builder">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
|
||||
@@ -22,9 +22,7 @@ describe('UX-04 control asistido', () => {
|
||||
return fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Periodo seleccionado'))!.query(By.directive(MatSelect));
|
||||
}
|
||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
it('UX-06C: el trigger muestra el periodo explícito y el borrador vacío no se aplica', async () => {
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S2'] },
|
||||
@@ -33,7 +31,6 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
||||
const values = Array.from(fixture.nativeElement.querySelectorAll('.select-value') as NodeListOf<HTMLElement>);
|
||||
expect(values.map(e => e.textContent)).toContain('2025-S2');
|
||||
expect(values.map(e => e.textContent)).toContain('Elegir periodo');
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'empty' },
|
||||
@@ -47,7 +44,7 @@ describe('UX-04 control asistido', () => {
|
||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||
fixture.changeDetectorRef.detach();
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
const select = periodSelect();
|
||||
@@ -83,7 +80,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||
control.changeMode('manual');
|
||||
control.select([]);
|
||||
control.year = '1'; control.unit = 'S1'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||
control.add();
|
||||
@@ -91,7 +88,7 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual(['0001-S1']);
|
||||
});
|
||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
||||
control.select([]); control.year = year; control.unit = unit; control.add();
|
||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||
@@ -99,14 +96,14 @@ describe('UX-04 control asistido', () => {
|
||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('conserva borradores independientes sin convertir periodos', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||
});
|
||||
it('un solo periodo: agregar otro lo reemplaza y varios se rechazan; elimina sin botones dentro de opciones', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
control.select(['2025-S1', '2025-S2']); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
@@ -125,7 +122,7 @@ describe('UX-04 control asistido', () => {
|
||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||
const edited = vi.spyOn(control.edited, 'emit');
|
||||
const apply = vi.spyOn(control.apply, 'emit');
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
@@ -134,11 +131,25 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('no ofrece Todos en meses cuando el primero es semestre', () => {
|
||||
control.changeTipo('mes'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
|
||||
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
|
||||
expect(labels).toContain('Intervalo de análisis');
|
||||
expect(labels).not.toContain('Modalidad');
|
||||
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
|
||||
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
|
||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
|
||||
expect(options).toEqual(['Semestral', 'Mensual']);
|
||||
select.componentInstance.close();
|
||||
});
|
||||
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||
options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
||||
fixture.detectChanges();
|
||||
control.changeTipo('mes');
|
||||
expect(control.selectedPeriods).toEqual(['2025-12']);
|
||||
control.select(['2025-11']); control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
// A period already chosen for that interval is kept.
|
||||
expect(control.selectedPeriods).toEqual(['2025-11']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,17 +42,15 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
get hasPending() { return pending(this.state); }
|
||||
get summary() { return describePeriods(this.state.tipo, this.entry.draft); }
|
||||
get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; }
|
||||
// There is no "every period" choice in the editor: a new interval starts on its most recent
|
||||
// period with a report (options are sorted newest first).
|
||||
changeTipo(tipo: TipoPeriodo) {
|
||||
if (!this.types.includes(tipo)) return;
|
||||
this.state.tipo = tipo;
|
||||
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
||||
this.year = this.unit = this.error = '';
|
||||
this.edited.emit();
|
||||
}
|
||||
changeMode(mode: 'todos' | 'manual') {
|
||||
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
|
||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
||||
this.error = '';
|
||||
if (this.entry.draft.mode !== 'explicit' && this.availability?.status === 'ready' && this.options.length)
|
||||
this.entry.draft = { mode: 'explicit', periodos: [this.options[0]] };
|
||||
this.edited.emit();
|
||||
}
|
||||
// Only one period can be chosen: cards and figures never combine periods.
|
||||
@@ -77,7 +75,6 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
}
|
||||
remove(period: string) {
|
||||
this.entry.added = this.entry.added.filter(p => p !== period);
|
||||
// Removing an unselected option must not change the Todos mode.
|
||||
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
||||
else this.edited.emit();
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); }
|
||||
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); }
|
||||
function draft(tipo: TipoPeriodo, periods: string[]) {
|
||||
const control = editor(); control.changeTipo(tipo); control.changeMode('manual');
|
||||
const control = editor(); control.changeTipo(tipo); control.select([]);
|
||||
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
|
||||
}
|
||||
function apply() { page.applyFilters(); fixture.detectChanges(); }
|
||||
@@ -67,7 +67,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
});
|
||||
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
|
||||
load(); open(); respond(); const result = panels()[0].result();
|
||||
editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0);
|
||||
editor().select([]); apply(); expect(page.filters!.applied.revision).toBe(0);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
draft('semestre', ['2025-S1']); fixture.detectChanges();
|
||||
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
@@ -114,7 +114,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
|
||||
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de tiempo mes');
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('intervalo de análisis mensual');
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
r.flush({ data: [], layout: {} });
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
|
||||
@@ -146,12 +146,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
requests.forEach(r => { expect(r.request.params.get('periodos')).toBe(periods[0]); r.flush('', { status: 404, statusText: 'Missing' }); });
|
||||
fixture.detectChanges(); expect(panels().slice(1).every(p => p.result().state === 'Sin datos del periodo')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicación manual posterior y Todos prevalecen sin repetir la búsqueda', () => {
|
||||
it('aplicación manual posterior prevalece sin repetir la búsqueda', () => {
|
||||
choose(); editor().select([periods[2]]); fixture.detectChanges(); http.expectNone(() => true);
|
||||
page.applyFilters(); fixture.detectChanges(); flushPanels(periods[2], definitions.length);
|
||||
expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: [periods[2]] });
|
||||
editor().changeMode('todos'); page.applyFilters(); fixture.detectChanges(); flushPanels(periods[0]);
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
|
||||
expect(panels().every(p => !p.initialPresentation)).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
|
||||
choose(); const applied = page.filters!.applied;
|
||||
|
||||
@@ -46,11 +46,11 @@ export type Compatibility = { compatible: true } | { compatible: false; reason:
|
||||
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
|
||||
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
|
||||
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
|
||||
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de tiempo ' + applied.tipo + ' del filtro general.' };
|
||||
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite el intervalo de análisis ' + (applied.tipo === 'mes' ? 'mensual' : 'semestral') + ' del filtro general.' };
|
||||
const mode = applied.selection.mode;
|
||||
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
|
||||
? 'Todos con reporte requiere semestre como primer intervalo de tiempo publicado. Para meses elige periodos explícitos.'
|
||||
: 'Los periodos del filtro general no son válidos para este intervalo de tiempo.' };
|
||||
? 'Todos con reporte requiere semestre como primer intervalo de análisis publicado. Para meses elige un periodo.'
|
||||
: 'Los periodos del filtro general no son válidos para este intervalo de análisis.' };
|
||||
return { compatible: true };
|
||||
}
|
||||
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
load('tea', harness); harness.detectChanges();
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.select([]); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
control.year = '2025'; control.unit = 'S2'; control.add();
|
||||
|
||||
@@ -205,7 +205,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control();
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||
a.select([]); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
const appliedA = request('f1');
|
||||
expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
|
||||
@@ -220,7 +220,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
|
||||
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const filters = control();
|
||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||
const result = panel.result();
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
@@ -238,7 +238,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
}
|
||||
});
|
||||
it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
|
||||
load([item]); toggle(); flushAll(); const a = control(); a.select([]); a.year = '2025'; a.unit = 'S1'; a.add();
|
||||
page.applyFilters(); fixture.detectChanges(); flushAll(); kpiMissing(); a.year = '2025'; a.unit = 'S2'; a.add();
|
||||
cards()[0].setVisible(false); fixture.detectChanges(); toggle();
|
||||
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S2']);
|
||||
@@ -261,7 +261,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
|
||||
});
|
||||
it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => {
|
||||
load(); toggle(); flushAll(); control().changeMode('manual');
|
||||
load(); toggle(); flushAll(); control().select([]);
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); flushAll();
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll();
|
||||
toggle(); page.changeDominio('tea'); fixture.detectChanges(); load();
|
||||
@@ -315,7 +315,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
load(syntheticCatalogs.tea);
|
||||
const index = cards().findIndex(c => c.indicador.id === id);
|
||||
toggle(index); flushAll();
|
||||
const c = control(); c.changeMode('manual'); fixture.detectChanges(); await fixture.whenStable();
|
||||
const c = control(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(c.canApply).toBe(false); http.expectNone(() => true);
|
||||
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
|
||||
|
||||
@@ -118,7 +118,7 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
expect(panels()).toHaveLength(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('No se pudo determinar el periodo inicial de cáncer cervicouterino');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
const control = editor(); control.changeMode('manual'); control.select(['2025-S2']);
|
||||
const control = editor(); control.select([]); control.select(['2025-S2']);
|
||||
expect(control.canApply).toBe(false);
|
||||
fixture.componentInstance.retryAvailability(); fixture.componentInstance.retryInitialPeriod(); fixture.detectChanges();
|
||||
const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos');
|
||||
|
||||
@@ -154,7 +154,7 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
|
||||
const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle();
|
||||
const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
|
||||
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
|
||||
filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle();
|
||||
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
|
||||
|
||||
@@ -55,6 +55,33 @@
|
||||
</section>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
<p class="meta">Rangos de referencia y efectos asociados de ejemplo, pendientes de validación médica.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<span class="nombre">{{ m.etiqueta }}</span>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.valor !== null) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
|
||||
} @else {
|
||||
<p class="valor">Sin registro de sueño en el estudio.</p>
|
||||
}
|
||||
@if (m.efectos.length) {
|
||||
<p class="efectos-titulo">Posibles efectos asociados</p>
|
||||
<ul class="efectos">
|
||||
@for (efecto of m.efectos; track efecto) { <li>{{ efecto }}</li> }
|
||||
</ul>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<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>
|
||||
|
||||
@@ -26,4 +26,17 @@ dt { color: var(--issste-text-secondary); } dd { margin: 0; text-align: end; fon
|
||||
.regiones li { padding: .2rem 0; }
|
||||
.regiones li span:last-child { float: inline-end; font-variant-numeric: tabular-nums; }
|
||||
.regiones .destacada { font-weight: 700; }
|
||||
h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5rem; padding: .1rem .5rem; border: 1px dashed var(--issste-border); border-radius: 999px;
|
||||
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: .6rem 0 .6rem .75rem; border-top: 1px solid var(--issste-border); border-inline-start: 4px solid 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: .25rem 1rem; font-weight: 600; }
|
||||
li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; }
|
||||
li[data-estado=normal] .estado { color: var(--issste-text-secondary); font-weight: 400; }
|
||||
li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font-weight: 400; font-style: italic; }
|
||||
.valor { margin: .25rem 0 0; font-size: .85rem; color: var(--issste-text-secondary); font-variant-numeric: tabular-nums; }
|
||||
.efectos-titulo { margin: .5rem 0 .25rem; font-size: .85rem; font-weight: 600; }
|
||||
.efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .85rem; }
|
||||
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; }
|
||||
|
||||
@@ -2,12 +2,13 @@ import { Component, DestroyRef, inject, Input, OnInit, signal } from '@angular/c
|
||||
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';
|
||||
import { TeaAdos2, TeaAlteracionEstado, 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 ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
|
||||
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.
|
||||
@@ -58,6 +59,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
readonly clasificacion = CLASIFICACION;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
readonly estado = ESTADO;
|
||||
ngOnInit() { this.load(); }
|
||||
load() {
|
||||
this.status.set('loading');
|
||||
@@ -66,5 +68,6 @@ export class TeaPacienteResumen implements OnInit {
|
||||
error: () => this.status.set('error'),
|
||||
});
|
||||
}
|
||||
alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); }
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
}
|
||||
|
||||
@@ -22,9 +22,9 @@ describe('Resumen TEA por periodo', () => {
|
||||
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('En el periodo 2025-S2, 409 pacientes tuvieron al menos una evaluación psicológica, con o sin diagnóstico.');
|
||||
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('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 %']);
|
||||
|
||||
@@ -14,9 +14,9 @@ interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; deta
|
||||
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
|
||||
En el periodo <span class="dato listo">{{ periodo }}</span>, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M23_pacientes_evaluados', '') }" />
|
||||
pacientes tuvieron al menos una evaluación psicológica, con o sin diagnóstico. De los pacientes con nota médica, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
|
||||
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
|
||||
<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.
|
||||
|
||||
@@ -24,10 +24,17 @@ export interface TeaAdos2 {
|
||||
clasificacion: 'autismo' | 'espectro_autista' | 'no_espectro'; css: number; nivel_css: 'minimo' | 'bajo' | 'moderado' | 'alto';
|
||||
}
|
||||
export interface TeaEegRegion { codigo: string; etiqueta: string; valor_z: number }
|
||||
// Mock: EEG metrics with placeholder reference ranges and associated effects, pending medical review.
|
||||
export type TeaAlteracionEstado = 'normal' | 'aumentado' | 'disminuido' | 'no_evaluable';
|
||||
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 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[];
|
||||
alteraciones: TeaEegAlteracion[];
|
||||
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 }
|
||||
@@ -72,6 +79,15 @@ function validAdos(a: unknown): boolean {
|
||||
return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0)
|
||||
&& a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0);
|
||||
}
|
||||
// A metric without a value cannot be evaluated; one with a value is out of range exactly when it is altered.
|
||||
function validAlteracion(a: unknown): boolean {
|
||||
if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !record(a['referencia'])
|
||||
|| !finite(a['referencia']['min']) || !finite(a['referencia']['max']) || (a['referencia']['min'] as number) > (a['referencia']['max'] as number)
|
||||
|| !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false;
|
||||
const estado = a['estado'];
|
||||
if (estado === 'no_evaluable') return a['valor'] === null && a['valor_z'] === null;
|
||||
return finite(a['valor']) && finite(a['valor_z']) && ['normal', 'aumentado', 'disminuido'].includes(estado as string);
|
||||
}
|
||||
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'])
|
||||
@@ -80,6 +96,7 @@ function validEeg(e: unknown): boolean {
|
||||
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 (!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
|
||||
|
||||
@@ -12,6 +12,12 @@ const data = {
|
||||
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 metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra });
|
||||
const alteraciones = [
|
||||
metrica('exponente_aperiodico', 'Exponente aperiódico', { valor: 0.9, valor_z: -2.4, estado: 'disminuido', efectos: ['Espectro más plano de lo esperado para la edad.'] }),
|
||||
metrica('husos_sueno', 'Husos del sueño', { valor: null, valor_z: null, estado: 'no_evaluable' }),
|
||||
metrica('entropia_multiescala', 'Entropía multiescala', { valor: 1.5, valor_z: 0.3, estado: 'normal' }),
|
||||
];
|
||||
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',
|
||||
@@ -19,7 +25,7 @@ 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, 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 }],
|
||||
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 }] } },
|
||||
};
|
||||
const anormal = { ...data, filtros: { alteraciones_eeg: 'anormal' }, paginacion: { ...data.paginacion, total_items: 1 }, items: [item] };
|
||||
@@ -103,6 +109,13 @@ describe('Seguimiento TEA', () => {
|
||||
expect(panel.textContent).toContain('Afecto social (AS)');
|
||||
expect(panel.textContent).toContain('Buena');
|
||||
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!;
|
||||
expect(metricas.textContent).toContain('Datos de ejemplo');
|
||||
expect(metricas.textContent).toContain('Disminuido');
|
||||
expect(metricas.textContent).toContain('Posibles efectos asociados');
|
||||
expect(metricas.textContent).toContain('Espectro más plano de lo esperado para la edad.');
|
||||
expect(metricas.textContent).toContain('Sin registro de sueño en el estudio.');
|
||||
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
|
||||
(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();
|
||||
@@ -130,4 +143,14 @@ describe('Seguimiento TEA', () => {
|
||||
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();
|
||||
});
|
||||
it('valida las alteraciones del EEG', () => {
|
||||
const con = (m: object) => ({ ...detalle, eeg: { ...detalle.eeg, alteraciones: [m] } });
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, alteraciones: undefined } }, 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], estado: 'alto' }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], valor: null }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[1], valor: 3 }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], referencia: { min: 3, max: 1 } }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(con(alteraciones[2]), 'T-0001')).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user