Merge dev into the CaCu risk record branch
dev already names the history tab «Trazabilidad» for the three domains, so its version of those files stays. CaCu's diagnosis-to-treatment time keeps one presentation, its card: it has no figure of its own next to the screening route chart.
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click.
|
||||
// Fixture: a host component that projects one line of text into the button.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
|
||||
@Component({ imports: [IndicadorAyuda], template: `<app-indicador-ayuda etiqueta="Cómo leer: prueba" (opened)="aperturas = aperturas + 1">Texto de ayuda</app-indicador-ayuda>` })
|
||||
class Host { aperturas = 0; }
|
||||
|
||||
describe('Ayuda redonda', () => {
|
||||
function crear() {
|
||||
const fixture = TestBed.createComponent(Host);
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const boton = () => root.querySelector<HTMLButtonElement>('.ayuda-boton')!;
|
||||
const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim();
|
||||
const ayuda = root.querySelector('.ayuda')!;
|
||||
return { fixture, boton, texto, ayuda };
|
||||
}
|
||||
|
||||
it('muestra el texto al pasar el cursor y lo oculta al salir', () => {
|
||||
// Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned.
|
||||
const { fixture, texto, ayuda } = crear();
|
||||
expect(texto()).toBeUndefined();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('un clic fija el texto hasta el siguiente clic', () => {
|
||||
// Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it.
|
||||
const { fixture, boton, texto, ayuda } = crear();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('true');
|
||||
boton().click(); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
|
||||
it('avisa solo al abrirse con un clic y nombra el botón', () => {
|
||||
// Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost.
|
||||
const { fixture, boton } = crear();
|
||||
boton().click(); boton().click(); boton().click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.aperturas).toBe(2);
|
||||
expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
|
||||
// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click.
|
||||
@Component({
|
||||
selector: 'app-indicador-ayuda',
|
||||
template: `
|
||||
<div class="ayuda" (mouseenter)="sobre.set(true)" (mouseleave)="sobre.set(false)" (focusin)="sobre.set(true)" (focusout)="sobre.set(false)">
|
||||
<button type="button" class="ayuda-boton" [attr.aria-label]="etiqueta()" [attr.aria-expanded]="visible()"
|
||||
[attr.aria-controls]="visible() ? idPanel : null" (click)="alternar()"><span aria-hidden="true">?</span></button>
|
||||
@if (visible()) {
|
||||
<div class="ayuda-texto" role="tooltip" [id]="idPanel"><ng-content /></div>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
styles: `
|
||||
:host { position: absolute; top: .5rem; right: .5rem; z-index: 2; }
|
||||
.ayuda { position: relative; }
|
||||
.ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0;
|
||||
border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||
.ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent);
|
||||
border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorAyuda {
|
||||
readonly etiqueta = input('Cómo leer');
|
||||
readonly opened = output<void>();
|
||||
readonly sobre = signal(false);
|
||||
readonly fijo = signal(false);
|
||||
private static contador = 0;
|
||||
readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador;
|
||||
visible() { return this.sobre() || this.fijo(); }
|
||||
alternar() {
|
||||
const abre = !this.fijo();
|
||||
this.fijo.set(abre);
|
||||
if (abre) this.opened.emit();
|
||||
}
|
||||
}
|
||||
@@ -24,16 +24,18 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
|
||||
const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados'];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
@if (!conteos) {
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
@@ -81,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.graphic-region { flex: 1; min-width: 0; }
|
||||
:host(.dual-card) { grid-column: 1 / -1; }
|
||||
:host(.doble) { grid-column: span 2; }
|
||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||
@@ -108,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
h2.con-ayuda { padding-right: 2.5rem; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
@@ -137,6 +141,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
}
|
||||
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||
get sobrio() { return true; }
|
||||
// TEA's stacked case charts span two columns of its three-column grid.
|
||||
get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<mat-card class="figure-card" [class.sin-marco]="ayudaRedonda" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected && ayudaRedonda) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + selected.titulo" (opened)="!metadata && metadataRequested.emit()">
|
||||
<ul class="ayuda-lista">@for (line of interpretation; track $index) { <li>{{ line }}</li> }</ul>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
@for (note of state.footnotes; track $index) { <p class="ayuda-nota">{{ note }}</p> }
|
||||
}
|
||||
</app-indicador-ayuda>
|
||||
} @else if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||
@@ -37,8 +44,10 @@
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
@if (!ayudaRedonda) {
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
}
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
@@ -84,7 +93,7 @@
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<div class="highlight-legend" [class.sin-estado]="ayudaRedonda" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; }
|
||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||
.interpretation { grid-row: 1; }
|
||||
.figure-legend { grid-row: 3; min-width: 0; }
|
||||
@@ -117,6 +118,7 @@
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
@@ -126,3 +128,6 @@
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
.ayuda-lista { margin: 0; padding-left: 1.1rem; }
|
||||
.ayuda-nota { margin: .5rem 0 0; }
|
||||
|
||||
@@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||
});
|
||||
|
||||
it('con la ayuda redonda no repite el título ni el nombre de la figura', () => {
|
||||
// Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title.
|
||||
fixture.componentRef.setInput('ayudaRedonda', true);
|
||||
ready({ data: [{ y: [1] }], layout: {} });
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('.figure-title')).toBeNull();
|
||||
expect(root.querySelector('.figure-id')).toBeNull();
|
||||
expect(root.querySelector('.ayuda-boton')).not.toBeNull();
|
||||
expect(root.querySelector('.interpretation')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
@@ -41,7 +42,7 @@ export interface FigureState {
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
@@ -142,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
// A round "?" button with the reading guide instead of the «Cómo leer» box.
|
||||
@Input() ayudaRedonda = false;
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
|
||||
@@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
// These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec.
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
@@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
|
||||
@@ -23,9 +23,10 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
host: { '[class.ayuda-externa]': 'conAyudaRedonda' },
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [class.sin-linea]="conAyudaRedonda" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@if (sidebar) {
|
||||
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||
@@ -110,7 +111,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
<app-indicador-figure-card [ayudaRedonda]="conAyudaRedonda" [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@@ -130,6 +131,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
:host { display: grid; min-width: 0; }
|
||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||
.sin-linea .panel-controls { border-top: 0; padding-block: 0; }
|
||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||
@@ -166,6 +168,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||
:host { container-type: inline-size; }
|
||||
// A container is a containing block for absolute children; the round help must reach the outer card.
|
||||
:host(.ayuda-externa) { container-type: normal; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
@@ -198,6 +202,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
// Round "?" help instead of the «Cómo leer» box; TEA draws it unless told otherwise.
|
||||
@Input() ayudaRedonda?: boolean;
|
||||
get conAyudaRedonda() { return this.ayudaRedonda ?? this.dominio === 'tea'; }
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
|
||||
@@ -59,8 +59,8 @@ describe('Dona de dos anillos para C1', () => {
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, tomado de la paleta compartida', () => {
|
||||
const colores = ['#A8C243', '#42C29C', '#9C42C2'];
|
||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||
|
||||
@@ -13,8 +13,8 @@ export const C2_PALETTE = Object.freeze({
|
||||
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||
]),
|
||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||
// Age groups of the EEG indicators (M21, M22): the same lime, teal and purple the other domains' series use.
|
||||
edades: Object.freeze(['#A8C243', '#42C29C', '#9C42C2']),
|
||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
||||
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied })) fixture.componentRef.setInput(name,value);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied, ayudaRedonda: false })) fixture.componentRef.setInput(name,value);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
|
||||
@@ -87,20 +87,6 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull();
|
||||
});
|
||||
|
||||
it('agrega la gráfica publicada de diagnóstico a tratamiento al final', () => {
|
||||
abrir([...CACU, item('cacu_dias_diagnostico_tratamiento', 'Tiempo de diagnóstico a tratamiento', 'C3r', ['fig_c3r_caja'])]);
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico',
|
||||
'catalog-card: Tiempo de diagnóstico a tratamiento']);
|
||||
});
|
||||
|
||||
it('conserva la ruta y muestra la gráfica publicada de diagnóstico a tratamiento', () => {
|
||||
abrir([...CACU, ...RUTA, item('cacu_dias_diagnostico_tratamiento', 'Tiempo de diagnóstico a tratamiento', 'C3r', ['fig_c3r_caja'])]);
|
||||
expect(root().querySelector('app-indicador-screening-route')).not.toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual(['catalog-card: Tiempo de diagnóstico a tratamiento']);
|
||||
});
|
||||
|
||||
it('Datos y definiciones conserva todo el catálogo', () => {
|
||||
// Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab.
|
||||
abrir(CACU);
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||
open('cama', CAMA);
|
||||
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6');
|
||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||
});
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
|
||||
@@ -217,7 +217,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||
]);
|
||||
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6, por paciente y por mastografía');
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.label)).toEqual(h3);
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import * as fx from './indicadores-fhir.fixtures';
|
||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
@@ -35,12 +36,12 @@ const curva = {
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
|
||||
outcome: { coding: [{ system: `${CS}/tea-ados2-resultado`, code: 'ados2_item_11', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=1' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
@@ -146,6 +147,24 @@ describe('Indicadores sobre FHIR', () => {
|
||||
const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {});
|
||||
for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta);
|
||||
expect(dibujo).not.toContain('Malo');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar']);
|
||||
});
|
||||
|
||||
it('presenta Aceptable en ambas gráficas cuando M29 lo declara como categoría propia', () => {
|
||||
const actual = measure('M29-calidad-eeg');
|
||||
const conAceptable: Measure = {
|
||||
...actual, extension: [...actual.extension ?? [], { url: `${SD}/categoria`, extension: [
|
||||
{ url: 'codigo', valueCode: 'ACEPTABLE' }, { url: 'etiqueta', valueString: 'ACEPTABLE' },
|
||||
] }],
|
||||
};
|
||||
const datos = datosDeReportes(conAceptable, [reports(fx.m29Semestres)[0]], 'semestre');
|
||||
expect(datos.filas.find(fila => fila['categoria'] === 'ACEPTABLE')).toMatchObject({ n: 0 });
|
||||
const figura = c2Figure(datos, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figura.status).toBe('supported');
|
||||
expect(JSON.stringify(figura.status === 'supported' ? figura.figure : {})).toContain('Aceptable');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar', 'Aceptable']);
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
@@ -329,7 +348,7 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
resultado: 'ados2_item_11', resultado_etiqueta: 'Mostrar', evento: '>=1', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
@@ -356,4 +375,13 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||
});
|
||||
|
||||
it('las regiones del mapa son las zonas del análisis del EEG', () => {
|
||||
// Pins down: Fz is its own region (frontal media) and the central region averages C3, Cz and C4 only, as the
|
||||
// EEG analysis's zones do, so a region on the map is the zone the association model names. Fails if Fz goes
|
||||
// back into the central average or the frontal media region disappears.
|
||||
const mapa = mapaDeElectrodos('picos_paroxisticos', 'Picos paroxísticos', { Fz: 3, C3: 1, Cz: 1.5, C4: 2 });
|
||||
expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([
|
||||
['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -62,7 +62,7 @@ const percent = (value: number | null) => value === null ? null : round1(value *
|
||||
// Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data.
|
||||
// TEA's EEG quality shows its invalid exams as «No aceptable».
|
||||
const ROTULOS_DE_CATEGORIA: Readonly<Record<string, Readonly<Record<string, string>>>> = {
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable' },
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable', ACEPTABLE: 'Aceptable' },
|
||||
};
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Presentation labels for representations confirmed in the published catalog.
|
||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
|
||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||
|
||||
@@ -81,13 +81,21 @@ describe('Histórico de CaMa', () => {
|
||||
});
|
||||
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual([
|
||||
'Días de la toma de la mastografía a su resultado',
|
||||
'Días del resultado de la mastografía al diagnóstico',
|
||||
'Días de tamizaje a diagnóstico',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'Resultado histopatológico',
|
||||
'Tasa de confirmación histopatológica',
|
||||
]);
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']);
|
||||
expect(paneles()).toHaveLength(7);
|
||||
const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo);
|
||||
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
|
||||
expect(graficas().some(g => g.label?.startsWith('Trazabilidad de ' + titulo))).toBe(true);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||
});
|
||||
|
||||
@@ -137,22 +137,27 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en
|
||||
});
|
||||
it('resultado histopatológico y mastografías BI-RADS 4, 5 ó 6 usan el pie de total por categoría', () => {
|
||||
// Fails if the two keep the old sentence, or if the patients' counts (which carry none) or another count gets it.
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría.';
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría';
|
||||
for (const id of ['cama_histopatologia_birads', 'cama_birads_456_mastografia']) expect(figura({ ...base('C2', MESES, cats), id } as IndicadorDatos).comoLeer).toBe(pie);
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe('');
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total');
|
||||
});
|
||||
it('M30 muestra la proporción publicada de alteraciones y deja pendiente la clasificación de EEG normal', () => {
|
||||
// Fails if children without an evaluable result are treated as normal through a complement.
|
||||
it('M30 dibuja EEG anormal y EEG normal como dos líneas complementarias', () => {
|
||||
// Fails if the normal line stops mirroring the abnormal one over the same denominator, or if a period without
|
||||
// evaluable children is drawn as normal (it stays a gap), or if the caption changes.
|
||||
const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }),
|
||||
fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos);
|
||||
const f = m30.figure as unknown as Fig;
|
||||
const lineas = f.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG con alteración detectada']);
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal', 'EEG normal']);
|
||||
expect(lineas[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(lineas[1]['y']).toEqual([37.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8');
|
||||
expect(JSON.stringify(lineas[1]['text'])).toContain('3 de 8');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]);
|
||||
expect(m30.comoLeer).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza (normal)')!['y']).toEqual([69.4, 13.7]);
|
||||
expect(m30.comoLeer).toBe('La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.');
|
||||
expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
export interface HistoricoFigura {
|
||||
contrato: string;
|
||||
figure: PlotlyFigure;
|
||||
comoLeer: string;
|
||||
notaMetodologica?: string;
|
||||
suprimidos: string[];
|
||||
sinDato: string[];
|
||||
}
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
|
||||
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
|
||||
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
|
||||
const FONDO_AZUL = '#9DBFE380';
|
||||
@@ -96,32 +94,44 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
|
||||
return { validas, suprimidos, sinDato };
|
||||
}
|
||||
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
|
||||
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
// CaMa's line charts (and TEA's, which follow them) share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
function colorDeLinea(id: string, tema: Tema) {
|
||||
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
|
||||
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
if (id.startsWith('cama_') || /^M\d+_/.test(id)) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
const linea = c2Theme(tema).line;
|
||||
return { linea, relleno: linea + '40' };
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
// Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions.
|
||||
const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0];
|
||||
|
||||
const PIE_PORCENTAJE: Readonly<Record<string, string>> = {
|
||||
cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.',
|
||||
[M30_RESULTADO_EEG]: 'Resultado experimental. La línea muestra EEG con alguna alteración detectada. La clasificación de EEG normal está pendiente de validación.',
|
||||
[M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
};
|
||||
const PIE_MEDIANA: Readonly<Record<string, string>> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id,
|
||||
'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.']));
|
||||
const PIE_CATEGORIAS: Readonly<Record<string, string>> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id,
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría.']));
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría']));
|
||||
|
||||
type Trazo = Omit<HistoricoFigura, 'contrato'>;
|
||||
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
const nombre = data.id === M30_RESULTADO_EEG ? 'EEG con alteración detectada' : 'Porcentaje';
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje');
|
||||
const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema);
|
||||
const resultadoEeg = data.id === M30_RESULTADO_EEG;
|
||||
const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje';
|
||||
const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10);
|
||||
// EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval.
|
||||
const normal = data.id === M30_RESULTADO_EEG ? [
|
||||
banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false,
|
||||
line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG },
|
||||
text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} %<br>%{text}<extra></extra>' },
|
||||
] : [];
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
@@ -132,8 +142,10 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
...normal,
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}),
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -219,25 +231,3 @@ export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: Hist
|
||||
if (!figura) throw new Error('Representación no soportada');
|
||||
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||
}
|
||||
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
|
||||
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
||||
const periodos = validar(data);
|
||||
const n = (periodo: string, categorias: readonly string[]) => {
|
||||
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
const puntos = periodos.map(periodo => {
|
||||
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
|
||||
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
|
||||
});
|
||||
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
|
||||
return {
|
||||
contrato: 'C1',
|
||||
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
|
||||
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
|
||||
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
|
||||
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Indicadores and Seguimiento, and its
|
||||
// Covers the history tab in the page: it sits between Indicadores and the risk analysis tab, and its
|
||||
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
|
||||
|
||||
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -46,10 +46,10 @@ describe('Pestaña Histórico', () => {
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
it('TEA tiene Trazabilidad y Análisis de Riesgo', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Covers the series chips of TEA's Trazabilidad: which series a figure offers and how choosing one dims the rest.
|
||||
// Fixture: a figure with two lines, each preceded by its confidence band, as the EEG normal/anormal chart draws it.
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { resaltarSerie, seriesDe } from './indicadores-historico';
|
||||
|
||||
const figura = (): PlotlyFigure => ({ layout: {}, data: [
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza' },
|
||||
{ type: 'scatter', name: 'EEG anormal', line: { color: '#a00' }, marker: { color: '#a00' } },
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza (normal)' },
|
||||
{ type: 'scatter', name: 'EEG normal', line: { color: '#06a' } },
|
||||
] });
|
||||
|
||||
describe('Series de la trazabilidad de TEA', () => {
|
||||
it('ofrece una ficha por línea o barra y ninguna por banda', () => {
|
||||
// Fails if a confidence band becomes a chip of its own or a series loses its colour.
|
||||
expect(seriesDe(figura())).toEqual([{ nombre: 'EEG anormal', color: '#a00' }, { nombre: 'EEG normal', color: '#06a' }]);
|
||||
});
|
||||
|
||||
it('al elegir una serie atenúa las demás y sus bandas, y deja intacta la figura publicada', () => {
|
||||
// Fails if the chosen series is dimmed, if its band is dimmed with the other series, or if the original is mutated.
|
||||
const original = figura();
|
||||
const vista = resaltarSerie(original, 'EEG normal');
|
||||
expect(vista.data.map(t => t['opacity'])).toEqual([.15, .15, undefined, undefined]);
|
||||
expect(original.data.every(t => t['opacity'] === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { Subject } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
@@ -86,22 +86,15 @@ describe('Figuras de histórico', () => {
|
||||
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
|
||||
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
|
||||
});
|
||||
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
|
||||
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
|
||||
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
|
||||
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
|
||||
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
|
||||
expect(figure.data[0]['y']).toEqual([75, 25]);
|
||||
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
|
||||
});
|
||||
it('una escala compartida fija el máximo de las medianas', () => {
|
||||
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
|
||||
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
|
||||
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
|
||||
});
|
||||
it('M21 y M22 no usan verde en sus líneas', () => {
|
||||
it('las líneas de M21 y M22 siguen el morado de las de CaMa', () => {
|
||||
// Fails if TEA's lines go back to their own age colours or leave CaMa's purple mark.
|
||||
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#9C42C2'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#9C42C2');
|
||||
});
|
||||
it('rechaza contratos sin representación y filas ambiguas', () => {
|
||||
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
|
||||
@@ -179,23 +172,45 @@ describe('Pestaña Histórico', () => {
|
||||
expect(c.ventana()).toBe(5);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
|
||||
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
|
||||
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
|
||||
it('ordena y titula las ocho gráficas de Trazabilidad y agrupa los tres pasos de tiempo', () => {
|
||||
const items: Indicador[] = [
|
||||
{ id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1' },
|
||||
{ id: 'M29_calidad_eeg', titulo: 'Calidad del EEG', contrato: 'C2' },
|
||||
{ id: 'M28_casos_por_estado', titulo: 'Casos por estatus', contrato: 'C2' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', titulo: 'Días de ADOS-2 a diagnóstico', contrato: 'C3r' },
|
||||
{ id: 'M26_dias_mchat_ados2', titulo: 'Días de M-CHAT a ADOS-2', contrato: 'C3r' },
|
||||
{ id: 'M25_dias_mchat_diagnostico', titulo: 'Días de M-CHAT a diagnóstico positivo', contrato: 'C3r' },
|
||||
{ id: 'M24_confirmacion_diagnostico', titulo: 'Porcentaje de confirmación diagnóstica', contrato: 'C1' },
|
||||
{ id: 'M23_pacientes_evaluados', titulo: 'Pacientes evaluados por resultado diagnóstico', contrato: 'C2' },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1' },
|
||||
{ id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1' },
|
||||
].map(item => ({ ...item, figuras: [], tipos_periodo: ['mes'] }));
|
||||
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
|
||||
const pasos = ['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo'];
|
||||
const titulos = () => Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.panel h2'), el => el.textContent?.trim());
|
||||
expect(titulos().slice(0, 3)).toEqual(pasos);
|
||||
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
|
||||
for (const { id } of items) {
|
||||
const c2 = id.startsWith('M28');
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
|
||||
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
|
||||
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
|
||||
for (const { id, contrato } of items) {
|
||||
const periodo = '2024-01';
|
||||
const fila = contrato === 'C1' ? c1(periodo, 50) : contrato === 'C2' ? c2(periodo, 'A', 3, 0)
|
||||
: { periodo, suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 };
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato, tipo_periodo: 'mes', periodos: [periodo], filas: [fila] });
|
||||
}
|
||||
render();
|
||||
const paneles = fixture.componentInstance.paneles();
|
||||
expect(paneles.map(p => p.item.id)).toEqual(['tiempos', 'M28_casos_por_estado', 'en_proceso']);
|
||||
expect(titulos()).toEqual([
|
||||
'Tiempos del tamizaje', 'Progresión del proceso diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Flujo del proceso diagnóstico y estudios de EEG', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal',
|
||||
]);
|
||||
const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
|
||||
expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos);
|
||||
// The notes live in the round help, not as text under the chart.
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')).toBeNull();
|
||||
const ayuda = (fixture.nativeElement as HTMLElement).querySelector('.panel:last-child app-indicador-ayuda') as HTMLElement;
|
||||
ayuda.querySelector('button')!.click(); fixture.detectChanges();
|
||||
expect(ayuda.querySelector('.ayuda-texto')!.textContent).toContain('Resultado experimental.');
|
||||
});
|
||||
it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => {
|
||||
// Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped.
|
||||
|
||||
@@ -7,14 +7,16 @@ import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { defer, map, Subscription } from 'rxjs';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
||||
import { TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD } from './indicadores-kpi';
|
||||
|
||||
export { HISTORICO_CAMA };
|
||||
|
||||
@@ -31,8 +33,11 @@ type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' }
|
||||
| { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
class ContratoHistoricoInvalido extends Error {}
|
||||
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
const CASOS = 'M28_casos_por_estado';
|
||||
const TIEMPOS = TEA_FIGURAS_OPORTUNIDAD;
|
||||
const TITULOS_TEA: Readonly<Record<string, string>> = {
|
||||
M23_pacientes_evaluados: 'Progresión del proceso diagnóstico',
|
||||
M28_casos_por_estado: 'Flujo del proceso diagnóstico y estudios de EEG',
|
||||
};
|
||||
const PERSONALIZADO = -1;
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p)));
|
||||
@@ -43,29 +48,46 @@ function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
||||
}
|
||||
|
||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
|
||||
// Keep the individual cards available for loading, error and empty states.
|
||||
function agruparTiempos(paneles: Panel[]): Panel[] {
|
||||
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
|
||||
const listos = pasos.every(p => p?.estado === 'listo');
|
||||
return paneles.flatMap((panel): Panel[] => {
|
||||
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
|
||||
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
|
||||
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos del tamizaje', contrato: 'C3r' }, pasos: figuras,
|
||||
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
|
||||
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
|
||||
}
|
||||
if (listos && TIEMPOS.includes(panel.item.id)) return [];
|
||||
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
|
||||
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||
}
|
||||
return [panel];
|
||||
});
|
||||
}
|
||||
|
||||
interface SerieResaltable { nombre: string; color: string }
|
||||
const nombreDe = (trazo: Record<string, unknown>) => typeof trazo['name'] === 'string' ? trazo['name'] : '';
|
||||
// Bands are drawn with their line: they are not series of their own.
|
||||
const esBanda = (trazo: Record<string, unknown>) => trazo['fill'] === 'toself';
|
||||
function colorDe(trazo: Record<string, unknown>): string {
|
||||
const marca = trazo['marker'] as { color?: unknown } | undefined, linea = trazo['line'] as { color?: unknown } | undefined;
|
||||
const color = typeof marca?.color === 'string' ? marca.color : linea?.color;
|
||||
return typeof color === 'string' ? color : 'currentColor';
|
||||
}
|
||||
export function seriesDe(figura: PlotlyFigure): SerieResaltable[] {
|
||||
return figura.data.filter(trazo => !esBanda(trazo) && nombreDe(trazo)).map(trazo => ({ nombre: nombreDe(trazo), color: colorDe(trazo) }));
|
||||
}
|
||||
// Dims every series but the chosen one; a band follows the line drawn right after it.
|
||||
export function resaltarSerie(figura: PlotlyFigure, elegida: string): PlotlyFigure {
|
||||
const data = figura.data.map((trazo, i) => {
|
||||
const propio = esBanda(trazo) ? nombreDe(figura.data[i + 1] ?? {}) : nombreDe(trazo);
|
||||
return propio === elegida ? trazo : { ...trazo, opacity: .15 };
|
||||
});
|
||||
return { ...figura, data };
|
||||
}
|
||||
|
||||
// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them.
|
||||
const ORDEN_TEA = ['tiempos', 'M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg',
|
||||
CASOS, 'en_proceso', 'M29_calidad_eeg', M30_RESULTADO_EEG];
|
||||
const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG];
|
||||
function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; };
|
||||
return paneles.map((panel, i) => ({ panel, i })).sort((a, b) => lugar(a.panel) - lugar(b.panel) || a.i - b.i).map(({ panel }) => panel);
|
||||
@@ -75,7 +97,7 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
||||
@Component({
|
||||
selector: 'app-indicadores-historico',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorAyuda],
|
||||
template: `
|
||||
<div class="controles compacto">
|
||||
<h2>Filtros</h2>
|
||||
@@ -99,6 +121,9 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<div class="paneles">
|
||||
@for (panel of paneles(); track panel.item.id) {
|
||||
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
||||
@if (dominio() === 'tea' && panel.estado === 'listo' && panel.figura.comoLeer) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + panel.item.titulo"><p class="ayuda-texto">{{ panel.figura.comoLeer }}@if (panel.figura.notaMetodologica) { {{ panel.figura.notaMetodologica }} }</p></app-indicador-ayuda>
|
||||
}
|
||||
<h2>{{ panel.item.titulo }}</h2>
|
||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||
@if (panel.mensaje) {
|
||||
@@ -117,15 +142,26 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<div class="pasos">
|
||||
@for (paso of pasos; track paso.titulo) {
|
||||
<section><h3>{{ paso.titulo }}</h3>
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="(dominio() === 'cacu' ? 'Trazabilidad de ' : 'Histórico de ') + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="etiquetaVista() + ' de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||
[label]="(dominio() === 'cacu' ? 'Trazabilidad de ' : 'Histórico de ') + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
@if (series(panel); as lista) {
|
||||
@if (dominio() === 'tea' && lista.length > 1) {
|
||||
<div class="series" role="group" aria-label="Resaltar una serie">
|
||||
@for (serie of lista; track serie.nombre) {
|
||||
<button type="button" [style.--swatch]="serie.color" [attr.aria-pressed]="resaltados()[panel.item.id] === serie.nombre" (click)="resaltar(panel.item.id, serie.nombre)">
|
||||
<span class="swatch" [style.background]="serie.color" aria-hidden="true"></span>{{ serie.nombre }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
||||
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
@if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
@@ -167,9 +203,9 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
|
||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
.panel { position: relative; box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; padding-right: 2.5rem; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.nota-pie { margin-top: var(--issste-space-3); padding-top: var(--issste-space-2); border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font-size: 0.8125rem; line-height: 1.4; }
|
||||
@@ -177,6 +213,14 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
.nota-pie summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.nota-pie p { margin-top: var(--issste-space-2); font: inherit; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
app-indicador-ayuda p { margin: 0; }
|
||||
.series { display: flex; flex-wrap: wrap; gap: .25rem .75rem; margin-top: var(--issste-space-3); }
|
||||
// The look of CaMa's category chips: rounded, outlined with the series colour, tinted when chosen.
|
||||
.series button { display: inline-flex; align-items: center; gap: .45rem; min-height: 36px; padding: .25rem .75rem; border: 1px solid color-mix(in srgb, var(--swatch) 55%, var(--issste-border));
|
||||
border-radius: .75rem; background: var(--issste-surface); color: inherit; font: inherit; font-size: .875rem; cursor: pointer; }
|
||||
.series button[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); font-weight: 600; }
|
||||
.series button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; }
|
||||
.panel.ancho { grid-column: 1 / -1; }
|
||||
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
@@ -186,12 +230,30 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
})
|
||||
export class IndicadoresHistorico {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
// The series each panel's chart draws, which a chip can highlight; one selection per panel.
|
||||
readonly resaltados = signal<Readonly<Record<string, string>>>({});
|
||||
series(panel: Panel): readonly SerieResaltable[] { return panel.estado === 'listo' ? seriesDe(panel.figura.figure) : []; }
|
||||
resaltar(id: string, nombre: string) {
|
||||
this.resaltados.update(actual => {
|
||||
const { [id]: previo, ...resto } = actual;
|
||||
return previo === nombre ? resto : { ...actual, [id]: nombre };
|
||||
});
|
||||
}
|
||||
// The figure of each panel with a selected series; the others keep their published figure untouched.
|
||||
readonly vistas = computed<Readonly<Record<string, PlotlyFigure>>>(() => {
|
||||
const elegidas = this.resaltados();
|
||||
return Object.fromEntries(this.paneles().flatMap(panel => {
|
||||
const nombre = elegidas[panel.item.id];
|
||||
return nombre && panel.estado === 'listo' ? [[panel.item.id, resaltarSerie(panel.figura.figure, nombre)]] : [];
|
||||
}));
|
||||
});
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
readonly catalogLoading = input(false);
|
||||
readonly catalogError = input('');
|
||||
readonly retryCatalog = output<void>();
|
||||
readonly etiquetaVista = computed(() => 'Trazabilidad');
|
||||
// What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog.
|
||||
private readonly config = computed(() => historicoDeDominio(this.dominio()));
|
||||
// The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active;
|
||||
@@ -260,7 +322,7 @@ export class IndicadoresHistorico {
|
||||
const visibles = this.recortar(carga.datos.periodos);
|
||||
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
|
||||
})) * 1.05;
|
||||
const panelDe = (item: Indicador): Panel & { datos?: IndicadorDatos } => {
|
||||
const panelDe = (item: Indicador): Panel => {
|
||||
if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' };
|
||||
const carga = cargas?.[item.id];
|
||||
if (!carga) return { item, estado: 'cargando' };
|
||||
@@ -284,7 +346,7 @@ export class IndicadoresHistorico {
|
||||
if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) {
|
||||
return { item, estado: mensaje ? 'error' : 'vacio', mensaje };
|
||||
}
|
||||
return { item, rango, estado: 'listo', figura, datos, mensaje };
|
||||
return { item, rango, estado: 'listo', figura, mensaje };
|
||||
} catch (error) {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
@@ -303,8 +365,10 @@ export class IndicadoresHistorico {
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
const paneles = agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
return this.dominio() === 'tea' ? ordenar(paneles, ORDEN_TEA) : paneles;
|
||||
const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||
if (this.dominio() !== 'tea') return items.map(panelDe);
|
||||
const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
return agruparTiempos(ordenar(paneles, ORDEN_TEA));
|
||||
});
|
||||
|
||||
constructor() {
|
||||
|
||||
@@ -80,7 +80,7 @@ describe('KPI de tratamiento de CaCu', () => {
|
||||
expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD);
|
||||
// the cards carry no provisional notice: what the measure is lives in its technical sheet
|
||||
expect(cards[1].textContent).not.toContain('Indicador provisional');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')?.textContent).not.toContain('diagnóstico a tratamiento');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')).toBeNull();
|
||||
expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally {
|
||||
|
||||
@@ -49,9 +49,8 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
// cards read the `titulo` that the API already sends.
|
||||
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
||||
// M28's last stage follows neuropediatrics and requires a good EEG.
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
||||
// M29's category of the EEGs the analysis found valid.
|
||||
export const M29_BUENO = 'BUENO';
|
||||
// What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality.
|
||||
@@ -73,7 +72,6 @@ export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' },
|
||||
{ id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento' },
|
||||
];
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry
|
||||
// with no `id` has no published indicator yet and draws as pending.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<section class="dashboard" [class.dominio-tea]="dominio === 'tea'" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
@if (fichaPacienteAbierta()) {
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
|
||||
@@ -34,6 +34,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
// TEA draws three smaller plots per row.
|
||||
.dominio-tea .catalog-grid { --plot-height: 340px; }
|
||||
@container dashboard (min-width: 1000px) { .dominio-tea .catalog-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-flow: dense; } }
|
||||
|
||||
@media (max-width: 550px) {
|
||||
h1 { font-size: 1.5rem; }
|
||||
|
||||
@@ -227,7 +227,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
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;
|
||||
// TEA's reading guide is the round "?" button: its first opening loads the metadata once.
|
||||
const button = fixture.nativeElement.querySelector('.ayuda-boton') as HTMLButtonElement;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
@@ -287,7 +288,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
|
||||
load(); toggle(); flushAll();
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle');
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .ayuda-boton');
|
||||
input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input);
|
||||
const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf<HTMLElement>).map(e => e.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
|
||||
@@ -37,6 +37,7 @@ import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { historicoDeDominio } from './indicadores-historico-config';
|
||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
import { M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
@@ -44,10 +45,11 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
|
||||
// between its history and its follow-up list.
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_CACU: typeof SECTIONS_WITH_HISTORY = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_TEA: typeof SECTIONS = [
|
||||
{ id: 'resumen', label: 'Resumen' }, { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
];
|
||||
const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
export const CAMA_ANALYSIS_ENABLED = false;
|
||||
// TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them.
|
||||
@@ -57,7 +59,7 @@ function ordenTea(catalog: Indicador[]): Indicador[] {
|
||||
return [...first, ...catalog.filter(item => !named.includes(item.id))];
|
||||
}
|
||||
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
|
||||
SECTIONS_WITH_HISTORY[0], { id: 'historico', label: 'Trazabilidad' },
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
|
||||
|
||||
@@ -68,7 +70,11 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.dominio === 'cacu' ? SECTIONS_CACU : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
|
||||
get sections(): typeof SECTIONS {
|
||||
if (this.dominio === 'tea') return SECTIONS_TEA;
|
||||
if (this.dominio === 'cacu') return SECTIONS_CACU;
|
||||
return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS;
|
||||
}
|
||||
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
|
||||
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
@@ -393,7 +399,7 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
|
||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => !item.vistas || item.vistas.includes('resumen')))
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => item.id !== M30_RESULTADO_EEG && (!item.vistas || item.vistas.includes('resumen'))))
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||
@@ -424,10 +430,10 @@ export class IndicadoresPage {
|
||||
return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo };
|
||||
});
|
||||
}
|
||||
// Preserve the route chart; individual figures require a published figure contract.
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length) return [];
|
||||
// With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to
|
||||
// each event. Without it, each time the catalog publishes with a figure keeps its own.
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => {
|
||||
if (this.screeningRouteAvailable && figura.id !== 'cacu_dias_diagnostico_tratamiento') return [];
|
||||
const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0);
|
||||
return item ? [{ item, titulo: item.titulo }] : [];
|
||||
});
|
||||
|
||||
@@ -163,7 +163,8 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
['Indicadores', dominio === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain.
|
||||
const esperadas = ['Indicadores', domain === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
const esperadas = domain === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
@@ -58,6 +58,10 @@ describe('Secciones compartidas por dominio', () => {
|
||||
harness.detectChanges();
|
||||
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
||||
expect(tracking.hidden).toBe(false);
|
||||
if (domain === 'tea') {
|
||||
expect(tracking.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA');
|
||||
expect(tracking.querySelector('select[name="estatus"]')?.closest('label')?.firstChild?.textContent?.trim()).toBe('Estatus de EEG');
|
||||
}
|
||||
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
|
||||
if (domain === 'cama') {
|
||||
// An unavailable cohort has no table and offers a retry.
|
||||
|
||||
@@ -48,16 +48,16 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
const titles = (selector: string) => [...root().querySelectorAll(selector + ' app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('las figuras de tiempo van en oportunidad y las clínicas en su orden, sin duplicarse', () => {
|
||||
// Fails if a figure is drawn in both sections, if either order changes, or if M30 (not named by the sections)
|
||||
// disappears instead of following the clinical ones.
|
||||
// M30 belongs to Trazabilidad even when the catalog publishes it.
|
||||
open('tea', TEA);
|
||||
expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']);
|
||||
expect(titles('.graphic-section')).toEqual([
|
||||
'Pacientes evaluados por resultado diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Casos por estatus', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal']);
|
||||
'Casos por estatus', 'Calidad del EEG']);
|
||||
expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
expect(fixture.componentInstance.catalogOrder().map(item => item.id)).not.toContain('M30_resultado_eeg');
|
||||
});
|
||||
|
||||
it('un indicador no publicado deja el resto en su orden', () => {
|
||||
@@ -73,12 +73,12 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
expect(root().querySelector('app-tea-resumen-periodo')).toBeNull();
|
||||
});
|
||||
|
||||
it('la primera pestaña se llama Indicadores en los tres dominios', () => {
|
||||
// Fails if the first tab goes back to «Resumen» in any domain, or changes its section id.
|
||||
it('la primera pestaña se llama Resumen en TEA e Indicadores en CaCu y CaMa', () => {
|
||||
// Fails if TEA's first tab loses its name, if CaCu or CaMa take it, or if the section id changes.
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) {
|
||||
open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]);
|
||||
const first = root().querySelector('[role="tab"]') as HTMLElement;
|
||||
expect(first.textContent?.trim()).toBe('Indicadores');
|
||||
expect(first.textContent?.trim()).toBe(domain === 'tea' ? 'Resumen' : 'Indicadores');
|
||||
expect(first.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,7 +3,14 @@
|
||||
[registrosTemporales]="pacienteDetalle.registrosTemporales()"
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
@if (teaFicha) {
|
||||
<section class="ficha-tea" aria-label="Resumen del paciente">
|
||||
<button type="button" (click)="volverDeTea()">Volver a Seguimiento</button>
|
||||
<h2>Paciente {{ teaFicha }}</h2>
|
||||
<app-tea-paciente-resumen [id]="teaFicha" modo="resumen" />
|
||||
</section>
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado' || !!teaFicha">
|
||||
@if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (dominio === 'cama') {
|
||||
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
|
||||
@@ -100,7 +107,8 @@
|
||||
<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>
|
||||
<span class="chevron" aria-hidden="true"></span></button>
|
||||
<button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirTea(item.id_seudonimo, $event)">{{ item.id_seudonimo }}</button></td>
|
||||
<td>{{ item.grupo_edad }}</td>
|
||||
<td><span class="estado-caso" [attr.data-estado]="item.estado_caso">{{ etiquetaEstado[item.estado_caso] }}</span>
|
||||
@if (item.pendientes.length) { <small>Falta: {{ item.pendientes.join(', ') }}</small> }</td>
|
||||
@@ -109,7 +117,7 @@
|
||||
<td>{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { <small>Módulo {{ item.modulo_ados2 }}</small> }</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="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" (completo)="abrirTea($event)" /></td></tr>
|
||||
}
|
||||
} @empty { <tr><td colspan="7">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
|
||||
@@ -29,7 +29,7 @@ nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top
|
||||
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
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 { display: inline-flex; align-items: center; 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); }
|
||||
@@ -42,3 +42,4 @@ tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(i
|
||||
@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); }
|
||||
// TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page.
|
||||
.ficha-tea > button { margin-bottom: .5rem; }
|
||||
|
||||
@@ -61,6 +61,9 @@ export class IndicadoresTracking implements OnChanges {
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
/** The TEA patient whose whole record shows in place of the list. */
|
||||
teaFicha?: string;
|
||||
private controlTea?: HTMLElement;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
@@ -141,6 +144,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
// Changing domain removes the table that holds CaMa's record, so the page is told here that no record shows.
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado' || this.camaFichaAbierta()) this.fichaPacienteAbierta.emit(false);
|
||||
this.camaFichaAbierta.set(false);
|
||||
if (this.teaFicha) this.fichaPacienteAbierta.emit(false);
|
||||
this.teaFicha = undefined; this.controlTea = undefined;
|
||||
this.pacienteDetalle.cerrar(); this.controlPaciente = 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 };
|
||||
@@ -188,6 +193,18 @@ export class IndicadoresTracking implements OnChanges {
|
||||
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;
|
||||
}
|
||||
abrirTea(id: string, evento?: Event) {
|
||||
evento?.stopPropagation();
|
||||
this.controlTea = evento?.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined;
|
||||
this.teaFicha = id;
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
volverDeTea() {
|
||||
this.teaFicha = undefined;
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
const control = this.controlTea;
|
||||
afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector });
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
|
||||
@@ -4,9 +4,79 @@
|
||||
<button type="button" (click)="load()">Reintentar resumen</button>
|
||||
}
|
||||
@if (status() === 'ready' && detalle(); as d) {
|
||||
<div class="resumen" [class.sin-eeg]="!d.eeg">
|
||||
<section class="panel ados" aria-label="Resumen ADOS-2">
|
||||
<h3>ADOS-2</h3>
|
||||
@if (modo === 'tarjetas') {
|
||||
<div class="tarjetas">
|
||||
<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: {{ clasificacionDe(a) }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
|
||||
</div>
|
||||
@for (dom of a.dominios; track dom.codigo) {
|
||||
<div class="dominio">
|
||||
<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>
|
||||
}
|
||||
} @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 }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
|
||||
<div class="headline">
|
||||
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
|
||||
<small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG.' }}</small>
|
||||
</div>
|
||||
<p class="cifras">{{ reglasFuera(e) }} de {{ delEstudio(e).length }} reglas del estudio fuera de rango · {{ canalesMalos(e).length }} {{ canalesMalos(e).length === 1 ? 'canal descartado' : 'canales descartados' }}</p>
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-label="Alteraciones del EEG">
|
||||
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ alteradas(e).length }} de {{ evaluables(e) }} métricas evaluadas fuera de la referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}).</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<ul class="alteradas">
|
||||
@for (m of alteradas(e); track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado"><span>{{ m.etiqueta }}</span><span class="estado">{{ estado[m.estado] }} · z = {{ cifras(m.valor_z) }}</span></li>
|
||||
}
|
||||
</ul>
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
|
||||
<section class="panel" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
@if (filasRelacion(rel); as filas) {
|
||||
@if (!filas.length) {
|
||||
<p class="sin-alteraciones">Ninguna zona alterada de este paciente tiene una asociación clara con el ADOS-2.</p>
|
||||
} @else {
|
||||
<p class="meta">{{ filas.length }} {{ filas.length === 1 ? 'asociación' : 'asociaciones' }} en zonas alteradas del paciente (modelo de {{ rel.n_cohorte }} niños).@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
<p class="principal"><strong>{{ filas[0].biomarcador }}</strong> · {{ filas[0].zona_etiqueta }} (z = {{ cifras(filas[0].valor_z) }}) con {{ filas[0].resultado_etiqueta }}:
|
||||
<span class="prob">{{ porcentaje(filas[0].probabilidad) }} %</span> de probabilidad, OR {{ cifras(filas[0].or) }}.</p>
|
||||
}
|
||||
}
|
||||
} @else { <p>Sin modelo de asociación disponible.</p> }
|
||||
</section>
|
||||
</div>
|
||||
<button type="button" class="completo" (click)="completo.emit(d.id_seudonimo)">Ver el resumen completo del paciente</button>
|
||||
} @else {
|
||||
<article class="documento" [attr.aria-label]="'Resumen del paciente ' + d.id_seudonimo">
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Datos del paciente</h2></summary>
|
||||
<dl>
|
||||
<dt>Identificador seudónimo</dt><dd>{{ d.id_seudonimo }}</dd>
|
||||
<dt>Grupo de edad</dt><dd>{{ d.grupo_edad || 'Sin dato' }}</dd>
|
||||
@if (d.eeg; as e) { <dt>Edad al EEG</dt><dd>{{ e.edad_meses ?? 'Sin dato' }}{{ e.edad_meses !== null && e.edad_meses !== undefined ? ' meses' : '' }}</dd> }
|
||||
</dl>
|
||||
</details>
|
||||
|
||||
<details class="seccion" open>
|
||||
<summary><h2>ADOS-2</h2></summary>
|
||||
@if (d.ados2; as a) {
|
||||
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
|
||||
<div class="headline">
|
||||
@@ -34,10 +104,10 @@
|
||||
</table>
|
||||
</details>
|
||||
} @else { <p>Sin evaluación ADOS-2 registrada.</p> }
|
||||
</section>
|
||||
</details>
|
||||
|
||||
<section class="panel calidad" aria-label="Calidad del EEG">
|
||||
<h3>Calidad del EEG</h3>
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Calidad del EEG</h2></summary>
|
||||
@if (d.eeg; as e) {
|
||||
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
|
||||
<div class="headline">
|
||||
@@ -56,77 +126,74 @@
|
||||
</ul>
|
||||
}
|
||||
} @else { <p>Sin EEG registrado.</p> }
|
||||
</section>
|
||||
</details>
|
||||
|
||||
@if (d.eeg; as e) {
|
||||
<div class="alteraciones-zona" [class.abierta]="abierto(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">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.</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">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.referencia; as r) {
|
||||
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
|
||||
} @else {
|
||||
<p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
|
||||
@if (d.eeg; as e) {
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h2></summary>
|
||||
<p class="meta">Referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}). Elige una alteración para ver sus zonas y la norma.</p>
|
||||
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
|
||||
<div class="alteraciones-lado">
|
||||
<ul class="metricas">
|
||||
@for (m of e.alteraciones; track m.codigo) {
|
||||
<li [attr.data-estado]="m.estado">
|
||||
<div class="metrica">
|
||||
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-pressed]="m.estado === 'no_evaluable' ? null : mapaElegido === m.codigo"
|
||||
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
|
||||
<span class="estado">{{ estado[m.estado] }}</span>
|
||||
</div>
|
||||
@if (m.referencia; as r) {
|
||||
<p class="valor">{{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ cifras(r.min) }}–{{ cifras(r.max) }}@if (r.mediana !== null) { (mediana {{ cifras(r.mediana) }}) } · z = {{ cifras(m.valor_z) }}</p>
|
||||
} @else {
|
||||
<p class="valor">@if (m.valor !== null) { {{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</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>
|
||||
}
|
||||
@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>
|
||||
</ul>
|
||||
<section class="graficos" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (!abierto(e)) { <p class="sin-grafico">La métrica elegida no tiene mapa ni norma por edad para mostrar.</p> }
|
||||
@if (mapaActual(e); as mapa) {
|
||||
<div class="grafico">
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@if (figura) {
|
||||
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'260px'"
|
||||
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
|
||||
@for (r of mapa.regiones; track r.codigo) {
|
||||
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ cifras(r.valor_z) }}</span></li>
|
||||
}
|
||||
</ol>
|
||||
</div>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@if (abierto(e)) {
|
||||
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
|
||||
@if (mapaActual(e) && normaActual(e)) {
|
||||
<div class="vistas" role="group" aria-label="Qué mostrar">
|
||||
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
|
||||
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
|
||||
@if (normaActual(e); as m) {
|
||||
<div class="grafico">
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ cifras(m.valor_z) }}).</p>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@if (vista === 'norma' && normaActual(e); as m) {
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<p class="leyenda-norma">La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura).
|
||||
El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).</p>
|
||||
} @else if (mapaActual(e); as mapa) {
|
||||
<h3>Zonas más afectadas</h3>
|
||||
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
|
||||
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
|
||||
@if (figura) {
|
||||
<app-plotly-chart [figure]="figura" [showNotes]="false" [style.--plot-height]="'260px'"
|
||||
[label]="'Mapa topográfico del EEG del paciente ' + d.id_seudonimo" />
|
||||
}
|
||||
<ol class="regiones" aria-label="Regiones ordenadas por desviación">
|
||||
@for (r of mapa.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>
|
||||
</details>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
|
||||
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
|
||||
@if (d.relacion_ados2; as rel) {
|
||||
<details class="seccion" open>
|
||||
<summary><h2>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h2></summary>
|
||||
<p class="meta">Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se
|
||||
asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2.
|
||||
No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}</p>
|
||||
@@ -144,9 +211,9 @@
|
||||
<tbody>
|
||||
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
|
||||
<tr [class.alterada]="zonaAlterada(f)">
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ cifras(f.valor_z) }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
|
||||
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td><span class="or">OR {{ cifras(f.or) }}</span><small>IC 95 % {{ cifras(f.ic_inf) }}–{{ cifras(f.ic_sup) }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td>
|
||||
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
|
||||
<span class="barra" aria-hidden="true">
|
||||
@@ -165,7 +232,8 @@
|
||||
probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0.
|
||||
Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.</p>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</article>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
:host { display: block; container: host / inline-size; }
|
||||
.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; }
|
||||
// The four cards side by side in one row; two by two and then stacked as the row narrows.
|
||||
.tarjetas { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .75rem; }
|
||||
@container host (max-width: 64rem) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@container host (max-width: 36rem) { .tarjetas { grid-template-columns: minmax(0, 1fr); } }
|
||||
.cifras { margin: 0; font-size: .85rem; }
|
||||
.alteradas { margin: 0; padding: 0; list-style: none; font-size: .85rem; }
|
||||
.alteradas li { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; padding: .25rem 0; border-top: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.alteradas .estado { color: #B3261E; font-weight: 400; }
|
||||
.principal { margin: 0; font-size: .85rem; }
|
||||
button.completo { margin-top: .75rem; padding: .35rem .75rem; color: var(--issste-accent); font-weight: 600; }
|
||||
// The full record: one collapsible section after another, no cards.
|
||||
.documento { max-width: 64rem; }
|
||||
.seccion { margin: 0; padding: .25rem 0 .75rem; border-bottom: 1px solid var(--issste-border); }
|
||||
.seccion > summary { margin: 0; }
|
||||
.seccion > summary h2 { margin: 0; font-size: 1.15rem; }
|
||||
.seccion > :not(summary) { margin-inline-start: 1.25rem; }
|
||||
.documento .metricas { grid-template-columns: minmax(0, 1fr); gap: 0; }
|
||||
.documento .metricas > li { border: 0; border-top: 1px solid var(--issste-border); border-radius: 0; padding: .5rem 0 .5rem .6rem; }
|
||||
.documento .metricas > li[data-estado=aumentado], .documento .metricas > li[data-estado=disminuido] { border-inline-start: 4px solid #B3261E; }
|
||||
.panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); }
|
||||
h3 { margin: 0 0 .15rem; font-size: 1rem; }
|
||||
.meta { margin: 0 0 .5rem; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
@@ -47,17 +65,12 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
|
||||
font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; }
|
||||
.sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; }
|
||||
.metricas, .efectos { margin: 0; padding: 0; list-style: none; }
|
||||
// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it.
|
||||
.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; }
|
||||
.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; }
|
||||
.marco-mapa { min-width: 0; overflow: hidden; }
|
||||
.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; }
|
||||
.mapa h3 { margin-top: 0; }
|
||||
@keyframes aparecer { from { opacity: 0; } }
|
||||
@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } }
|
||||
@container host (max-width: 42rem) { .mapa { width: 100cqw; } }
|
||||
@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } }
|
||||
@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } }
|
||||
// The full summary: the metric list on the left, the plots of the chosen metric on the right, always in view.
|
||||
.alteraciones-lado { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); gap: 1.5rem; align-items: start }
|
||||
@container host (max-width: 52rem) { .alteraciones-lado { grid-template-columns: minmax(0, 1fr); } }
|
||||
.graficos { min-width: 0; display: grid; gap: 1rem; }
|
||||
.grafico h3 { margin-top: 0; }
|
||||
.sin-grafico { margin: 0; font-size: .9rem; color: var(--issste-text-secondary); }
|
||||
.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; }
|
||||
.metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; }
|
||||
.metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); }
|
||||
@@ -65,7 +78,9 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re
|
||||
.metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; }
|
||||
.metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; }
|
||||
li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; }
|
||||
li[data-estado=normal] .estado { color: var(--issste-text-secondary); font-weight: 400; }
|
||||
li[data-estado=normal] .estado { color: #1B7F3B; font-weight: 600; }
|
||||
:host-context([data-theme=dark]) li[data-estado=normal] .estado { color: #6FD38A; }
|
||||
@media (prefers-color-scheme: dark) { :host-context(:root:not([data-theme=light])) li[data-estado=normal] .estado { color: #6FD38A; } }
|
||||
li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font-weight: 400; font-style: italic; }
|
||||
.valor { margin: .1rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); font-variant-numeric: tabular-nums; }
|
||||
.efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; }
|
||||
@@ -88,9 +103,4 @@ button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border
|
||||
.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); }
|
||||
.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); }
|
||||
.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); }
|
||||
// The switch between the head map and the age norm, when the metric has both.
|
||||
.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; }
|
||||
.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; }
|
||||
.vistas button + button { border-inline-start: 1px solid var(--issste-border); }
|
||||
.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; }
|
||||
.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core';
|
||||
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, output, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
@@ -86,6 +86,10 @@ export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure {
|
||||
})
|
||||
export class TeaPacienteResumen implements OnInit {
|
||||
@Input({ required: true }) id = '';
|
||||
/** `tarjetas`: four summary cards for a table row. `resumen`: the whole record as a summary with collapsible headers. */
|
||||
@Input() modo: 'tarjetas' | 'resumen' = 'tarjetas';
|
||||
/** The cards' button: the host shows the whole record in its own section. */
|
||||
readonly completo = output<string>();
|
||||
private readonly service = inject(TeaSeguimientoService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||||
@@ -101,8 +105,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
}
|
||||
return '#FFFFFF';
|
||||
}
|
||||
// The side panel shows the chosen metric's head map, its age norm, or both with a switch between them.
|
||||
vista: 'zonas' | 'norma' = 'zonas';
|
||||
// The chosen metric's head map and its age norm, whichever it has.
|
||||
figuraNorma?: PlotlyFigure;
|
||||
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||||
// The age norm can only be drawn with the curve, the patient's value and their age.
|
||||
@@ -115,15 +118,13 @@ export class TeaPacienteResumen implements OnInit {
|
||||
private mostrar(eeg: TeaEeg, codigo: string | undefined) {
|
||||
const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo);
|
||||
this.mapaElegido = mapa || norma ? codigo : undefined;
|
||||
this.vista = mapa ? 'zonas' : 'norma';
|
||||
this.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||||
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
|
||||
}
|
||||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||||
// The chosen card closes the panel again, and the cards take the whole space back.
|
||||
this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo);
|
||||
// In the cards' accordion the chosen metric closes its panel again; in the full summary the plots stay in view.
|
||||
this.mostrar(eeg, this.modo === 'tarjetas' && codigo === this.mapaElegido ? undefined : codigo);
|
||||
}
|
||||
verVista(vista: 'zonas' | 'norma') { this.vista = vista; }
|
||||
readonly clasificacion = CLASIFICACIONES_ADOS2;
|
||||
readonly nivelCss = NIVEL_CSS;
|
||||
readonly calidad = CALIDAD;
|
||||
@@ -146,6 +147,8 @@ export class TeaPacienteResumen implements OnInit {
|
||||
}
|
||||
// The study-wide checks, then each bad channel.
|
||||
delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); }
|
||||
// Three significant digits, without trailing zeros.
|
||||
cifras(n: number | null | undefined) { return typeof n === 'number' ? String(Number(n.toPrecision(3))) : ''; }
|
||||
canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); }
|
||||
valorDe(c: TeaCriterioCalidad) {
|
||||
return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor;
|
||||
@@ -155,6 +158,9 @@ export class TeaPacienteResumen implements OnInit {
|
||||
return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.';
|
||||
}
|
||||
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
|
||||
// How many of the study-wide checks are out of range, and how many metrics could be judged against the age norm.
|
||||
reglasFuera(eeg: TeaEeg) { return this.delEstudio(eeg).filter(c => c.nivel === 'malo').length; }
|
||||
evaluables(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado !== 'no_evaluable').length; }
|
||||
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; }
|
||||
|
||||
@@ -165,7 +171,7 @@ export class TeaPacienteResumen implements OnInit {
|
||||
return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad';
|
||||
}
|
||||
porcentaje(p: number) { return Math.round(100 * p); }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; }
|
||||
qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${this.cifras(q)}`; }
|
||||
observado(f: TeaRelacionAdos2) {
|
||||
if (f.observado === null) return 'Sin dato';
|
||||
if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)';
|
||||
|
||||
@@ -13,9 +13,9 @@ const listo = (value: string | number, period = '2025-S2'): Result => ({ state:
|
||||
const c1 = (value: string, numerador: number, denominador: number): Result => ({ ...listo(value), numerador, denominador });
|
||||
|
||||
describe('Resumen TEA por periodo', () => {
|
||||
function render(paneles: IndicadorKpiPanel[]) {
|
||||
function render(paneles: IndicadorKpiPanel[], periodo = '2025-S2') {
|
||||
const fixture = TestBed.createComponent(TeaResumenPeriodo);
|
||||
fixture.componentRef.setInput('periodo', '2025-S2'); fixture.componentRef.setInput('paneles', paneles);
|
||||
fixture.componentRef.setInput('periodo', periodo); fixture.componentRef.setInput('paneles', paneles);
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
@@ -27,9 +27,9 @@ describe('Resumen TEA por periodo', () => {
|
||||
panel('M21_diagnosticados_con_eeg', c1('71.9', 41, 57)), panel('M22_diagnosticados_sin_eeg', c1('28.1', 16, 57)),
|
||||
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14)),
|
||||
panel('M29_calidad_eeg', { ...listo(80), categorias: { BUENO: 20, MALO: 50, SIN_ANALIZAR: 10 } })];
|
||||
const texto = (root: HTMLElement) => root.textContent!.replace(/\s+/g, ' ');
|
||||
const texto = (root: HTMLElement) => Array.from(root.querySelectorAll('p'), p => p.textContent!.replace(/\s+/g, ' ').trim()).join(' ');
|
||||
|
||||
it('redacta los dos párrafos con cada población y resalta los valores', () => {
|
||||
it('identifica el denominador de cada medida y resalta los valores publicados', () => {
|
||||
// Fails if a sentence reads another indicator's figure, if the stages stop adding up to the children evaluated
|
||||
// or if a median is cut (22.5 stays 22.5).
|
||||
const root: HTMLElement = render(completos()).nativeElement;
|
||||
@@ -37,11 +37,12 @@ describe('Resumen TEA por periodo', () => {
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('*tomando la mediana de los tiempos');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '25.0%']);
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
expect(root.querySelector('h2')!.textContent).toBe('Resumen');
|
||||
});
|
||||
|
||||
it('no copia cifras de ejemplo: otros conteos cambian toda la redacción', () => {
|
||||
@@ -50,11 +51,13 @@ describe('Resumen TEA por periodo', () => {
|
||||
panel('M28_casos_por_estado', { ...listo(3), categorias: { EEG: 0, SOLO_MCHAT: 1, PSICOLOGIA: 1, NEUROPEDIATRIA: 1 } }),
|
||||
panel('M24_confirmacion_diagnostico', c1('50.0', 1, 2)), panel('M25_dias_mchat_diagnostico', listo(31)),
|
||||
panel('M21_diagnosticados_con_eeg', c1('0.0', 0, 1)), panel('M22_diagnosticados_sin_eeg', c1('100.0', 1, 1)),
|
||||
panel('M26_dias_mchat_ados2', listo(5)), panel('M27_dias_ados2_diagnostico', listo(9)),
|
||||
panel('M26_dias_mchat_ados2', listo(54.5)), panel('M27_dias_ados2_diagnostico', listo(9)),
|
||||
panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })];
|
||||
const text = texto(render(paneles).nativeElement);
|
||||
const periodo = '2026-03';
|
||||
for (const p of paneles) p.result.set({ ...p.result(), period: periodo });
|
||||
const text = texto(render(paneles, periodo).nativeElement);
|
||||
expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.');
|
||||
for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo);
|
||||
});
|
||||
|
||||
@@ -64,10 +67,18 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57));
|
||||
paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0');
|
||||
});
|
||||
|
||||
it('incluye los estudios sin analizar en el total de EEG del periodo', () => {
|
||||
// Fails if the share of good quality leaves the unanalysed studies out of its denominator.
|
||||
const paneles = completos();
|
||||
paneles[7].result.set({ ...listo(6), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 6 } });
|
||||
expect(texto(render(paneles).nativeElement))
|
||||
.toContain('estudios de EEG, 0.0% tienen buena calidad.');
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
// Fails if a suppressed, foreign-period or unpublished figure is drawn as a number, or if its reason is lost.
|
||||
const paneles = completos();
|
||||
@@ -75,17 +86,25 @@ describe('Resumen TEA por periodo', () => {
|
||||
paneles[2].result.set(listo(30, '2025-S1'));
|
||||
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M29_calidad_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(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Sin datos para el periodo seleccionado', 'Indicador no publicado']);
|
||||
expect(root.textContent).not.toContain('30 días');
|
||||
});
|
||||
|
||||
it('una respuesta de otro periodo no invalida los conteos vigentes de M21', () => {
|
||||
const paneles = completos();
|
||||
paneles[4].result.set({ ...c1('28.1', 16, 58), period: '2025-S1' });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG');
|
||||
expect(root.querySelector('.dato.sin-dato')?.getAttribute('title')).toBe('Sin datos para el periodo seleccionado');
|
||||
});
|
||||
|
||||
it('no muestra los conteos de M21 y M22 si no hablan de los mismos niños', () => {
|
||||
// Fails if the confirmed children of M21 and of M22 disagree and the summary still prints them as one population.
|
||||
const paneles = completos();
|
||||
paneles[4].result.set(c1('28.1', 16, 58));
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title')))
|
||||
.toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
.toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
});
|
||||
|
||||
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||
|
||||
@@ -16,7 +16,8 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
selector: 'app-tea-resumen-periodo',
|
||||
imports: [MatButtonModule, NgTemplateOutlet],
|
||||
template: `
|
||||
<article class="resumen" [attr.aria-busy]="cargando">
|
||||
<article class="resumen" [attr.aria-busy]="cargando" aria-labelledby="tea-resumen-titulo">
|
||||
<h2 id="tea-resumen-titulo">Resumen</h2>
|
||||
<p>
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños entre 16 y 36 meses;
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> únicamente tienen M-CHAT,
|
||||
@@ -29,10 +30,10 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
<br>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado al cierre del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEeg() }" /> tienen un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEeg() }" /> aún no cuentan con uno de esa calidad.
|
||||
Del total de estudios de EEG del periodo,
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado en este periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> presentan estudio de EEG y faltan
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEegBueno() }" /> por realizarlo.
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: conEegBueno() }" /> estudios de EEG,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
</p>
|
||||
<p class="nota">*tomando la mediana de los tiempos</p>
|
||||
@@ -48,6 +49,7 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2
|
||||
: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); }
|
||||
h2 { margin: 0 0 var(--issste-space-3); font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; }
|
||||
p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; }
|
||||
p + p { margin-top: var(--issste-space-4); }
|
||||
p.nota { margin-top: var(--issste-space-2); font-size: .95rem; line-height: 1.5; color: var(--issste-text-secondary); }
|
||||
@@ -70,8 +72,9 @@ export class TeaResumenPeriodo {
|
||||
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)
|
||||
if (result.state !== 'Disponible' || result.value === undefined)
|
||||
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
|
||||
if (result.period !== this.periodo) return this.sinDato('Sin datos para el periodo seleccionado');
|
||||
return undefined;
|
||||
}
|
||||
private sinDato(detalle: string): Valor { return { texto: 'sin dato', estado: 'sin_dato', detalle }; }
|
||||
@@ -90,6 +93,7 @@ export class TeaResumenPeriodo {
|
||||
}
|
||||
// M21 and M22 split the same confirmed children, so a count of either is only shown while their denominators agree.
|
||||
private poblacionComun(): boolean {
|
||||
if (this.fallo(M21) || this.fallo(M22)) return true;
|
||||
const a = this.panel(M21)?.result(), b = this.panel(M22)?.result();
|
||||
return !(a?.denominador !== undefined && b?.denominador !== undefined && a.denominador !== b.denominador);
|
||||
}
|
||||
@@ -103,8 +107,8 @@ export class TeaResumenPeriodo {
|
||||
// Children with a confirmed diagnosis at the period's end, the denominator of M21 and M22.
|
||||
confirmados() { return this.conteo(M21, 'denominador'); }
|
||||
// Of them, those with a good EEG (M21's numerator) and those without yet (M22's).
|
||||
conEeg() { return this.conteo(M21, 'numerador'); }
|
||||
sinEeg() { return this.conteo(M22, 'numerador'); }
|
||||
conEegBueno() { return this.conteo(M21, 'numerador'); }
|
||||
sinEegBueno() { return this.conteo(M22, 'numerador'); }
|
||||
// The share of the period's EEGs (M29 counts exams, not patients) the analysis found valid.
|
||||
buenaCalidad(): Valor {
|
||||
const base = this.valor(M29, '');
|
||||
|
||||
@@ -35,7 +35,8 @@ const CRITERIOS = 'urn:tea:validation';
|
||||
const FILTRO_EEG: Record<string, string> = { sin_eeg_valido: 'sin-eeg-valido' };
|
||||
const INTERPRETACION: Record<string, TeaAlteracionEstado> = { H: 'aumentado', L: 'disminuido', N: 'normal' };
|
||||
|
||||
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average.
|
||||
// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average,
|
||||
// the scalp zones of the EEG analysis (`tea.contracts.ZONES`).
|
||||
export const ELECTRODOS: Record<string, [number, number]> = {
|
||||
Fp1: [-.25, .77], Fp2: [.25, .77], F7: [-.65, .47], F3: [-.33, .4], Fz: [0, .38], F4: [.33, .4], F8: [.65, .47],
|
||||
T3: [-.8, 0], C3: [-.4, 0], Cz: [0, 0], C4: [.4, 0], T4: [.8, 0],
|
||||
@@ -43,7 +44,8 @@ export const ELECTRODOS: Record<string, [number, number]> = {
|
||||
};
|
||||
const REGIONES: [string, string, string[]][] = [
|
||||
['frontal_izq', 'Frontal izquierda', ['Fp1', 'F3', 'F7']], ['frontal_der', 'Frontal derecha', ['Fp2', 'F4', 'F8']],
|
||||
['central', 'Central', ['Fz', 'C3', 'Cz', 'C4']], ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']],
|
||||
['frontal_media', 'Frontal media', ['Fz']], ['central', 'Central', ['C3', 'Cz', 'C4']],
|
||||
['temporal_izq', 'Temporal izquierda', ['T3', 'T5']],
|
||||
['temporal_der', 'Temporal derecha', ['T4', 'T6']], ['parietal', 'Parietal', ['P3', 'Pz', 'P4']], ['occipital', 'Occipital', ['O1', 'O2']],
|
||||
];
|
||||
const EJE = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service';
|
||||
import { mapaFigure } from './tea-paciente-resumen';
|
||||
import { mapaFigure, TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
|
||||
@@ -57,6 +57,16 @@ describe('Seguimiento TEA', () => {
|
||||
return fixture;
|
||||
}
|
||||
const request = () => http.expectOne(r => r.url === '/tea/seguimiento');
|
||||
// The patient's whole record, as the window opened from the patient id shows it.
|
||||
function resumen(d: object, id = 'T-0001') {
|
||||
const fixture = TestBed.createComponent(TeaPacienteResumen);
|
||||
fixture.componentRef.setInput('id', id); fixture.componentRef.setInput('modo', 'resumen');
|
||||
fixture.detectChanges();
|
||||
http.expectOne(`/tea/seguimiento/${id}`).flush(d); fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
const seccion = (root: HTMLElement, titulo: string) =>
|
||||
Array.from(root.querySelectorAll<HTMLDetailsElement>('details.seccion')).find(d => d.querySelector('summary h2')!.textContent!.trim().startsWith(titulo))!;
|
||||
it('muestra las siete columnas y los valores ausentes como No disponible', () => {
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
@@ -146,17 +156,15 @@ describe('Seguimiento TEA', () => {
|
||||
expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' });
|
||||
http.verify();
|
||||
});
|
||||
it('abre con las zonas de la primera alteración, cambia al elegir otra y se cierra al repetirla', () => {
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
it('el resumen muestra las alteraciones y sus gráficas lado a lado, siempre a la vista: elegir otra las cambia y repetirla las deja', () => {
|
||||
const fixture = resumen(detalle);
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
const lado = root.querySelector('.alteraciones-lado')!;
|
||||
expect(lado.querySelector('ul.metricas')).not.toBeNull();
|
||||
expect(lado.querySelector('section.graficos')).not.toBeNull();
|
||||
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true);
|
||||
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true');
|
||||
const panel = () => root.querySelector('section.mapa')!;
|
||||
expect(panel().classList.contains('panel')).toBe(false);
|
||||
const panel = () => root.querySelector('section.graficos')!;
|
||||
expect(tarjetas[0].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(panel().textContent).toContain('Azul: menos actividad');
|
||||
expect(panel().textContent).toContain('Rojo: más actividad');
|
||||
expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior');
|
||||
@@ -164,45 +172,38 @@ describe('Seguimiento TEA', () => {
|
||||
tarjetas[3].click(); fixture.detectChanges();
|
||||
expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos');
|
||||
expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital');
|
||||
expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false');
|
||||
expect(tarjetas[0].getAttribute('aria-pressed')).toBe('false');
|
||||
expect(tarjetas[1].disabled).toBe(true);
|
||||
expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false);
|
||||
expect(tarjetas[1].hasAttribute('aria-pressed')).toBe(false);
|
||||
// Choosing the same metric again keeps its plots in view.
|
||||
tarjetas[3].click(); fixture.detectChanges();
|
||||
expect(root.querySelector('section.mapa')).toBeNull();
|
||||
expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false);
|
||||
tarjetas[0].click(); fixture.detectChanges();
|
||||
expect(root.querySelector('section.mapa')).not.toBeNull();
|
||||
expect(panel().querySelector('.regiones')).not.toBeNull();
|
||||
expect(tarjetas[3].getAttribute('aria-pressed')).toBe('true');
|
||||
http.verify();
|
||||
});
|
||||
it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
|
||||
it('muestra el mapa y la norma por edad juntos cuando la métrica tiene los dos, o solo la norma si no tiene mapa, y rechaza una curva cuyos percentiles se cruzan', () => {
|
||||
const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48],
|
||||
p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] };
|
||||
const conCurva = detalle.eeg.alteraciones.map(m =>
|
||||
m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m);
|
||||
const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } };
|
||||
const fixture = open();
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const fixture = resumen(conNorma);
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges();
|
||||
const panel = () => root.querySelector('section.mapa')!;
|
||||
const vistas = () => panel().querySelectorAll<HTMLButtonElement>('.vistas button');
|
||||
// Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age.
|
||||
expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']);
|
||||
expect(panel().textContent).toContain('Zonas más afectadas');
|
||||
vistas()[1].click(); fixture.detectChanges();
|
||||
expect(vistas()[1].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad');
|
||||
const panel = () => root.querySelector('section.graficos')!;
|
||||
const titulos = () => Array.from(panel().querySelectorAll('h3')).map(h => h.textContent);
|
||||
// Ritmo has both: the map and the norm show together, with the patient's value and age, and no switch between them.
|
||||
expect(titulos()).toEqual(['Zonas más afectadas', 'Norma por edad']);
|
||||
expect(panel().querySelector('.vistas')).toBeNull();
|
||||
expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)');
|
||||
expect(panel().querySelector('.regiones')).toBeNull();
|
||||
// Gradiente has no map: its card opens the norm alone, without the switch.
|
||||
expect(panel().querySelector('.regiones')).not.toBeNull();
|
||||
// Gradiente has no map: its norm shows alone.
|
||||
const tarjetas = root.querySelectorAll<HTMLButtonElement>('button.nombre');
|
||||
tarjetas[4].click(); fixture.detectChanges();
|
||||
expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true');
|
||||
expect(vistas().length).toBe(0);
|
||||
expect(tarjetas[4].getAttribute('aria-pressed')).toBe('true');
|
||||
expect(titulos()).toEqual(['Norma por edad']);
|
||||
expect(panel().textContent).toContain('Gradiente anteroposterior');
|
||||
const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance;
|
||||
const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[];
|
||||
const c = fixture.componentInstance;
|
||||
const trazas = c.figuraNorma!.data as { name: string; x: number[]; y: number[] }[];
|
||||
expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']);
|
||||
expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]);
|
||||
const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m);
|
||||
@@ -215,14 +216,55 @@ describe('Seguimiento TEA', () => {
|
||||
expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)');
|
||||
expect(marco()).toBe('#FFFFFF');
|
||||
});
|
||||
it('redondea a tres cifras significativas', () => {
|
||||
// Fails if the alterations show more than three significant digits or keep trailing zeros.
|
||||
const c = TestBed.createComponent(TeaPacienteResumen).componentInstance;
|
||||
expect([c.cifras(0.123456), c.cifras(12.3456), c.cifras(1234.5), c.cifras(2), c.cifras(null)]).toEqual(['0.123', '12.3', '1230', '2', '']);
|
||||
});
|
||||
|
||||
it('sin alteraciones abre con la primera métrica evaluable', () => {
|
||||
const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m);
|
||||
const fixture = resumen({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } });
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('section.graficos .meta')!.textContent).toContain('Ritmo posterior');
|
||||
http.verify();
|
||||
});
|
||||
it('el identificador abre el resumen completo en su propia sección, sin desplegar la fila, y Volver regresa a la lista', () => {
|
||||
const fixture = open();
|
||||
const ficha = vi.fn(); fixture.componentInstance.fichaPacienteAbierta.subscribe(ficha);
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLButtonElement>('button.row-toggle')!.click(); fixture.detectChanges();
|
||||
const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m);
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); fixture.detectChanges();
|
||||
expect(root.querySelector('section.mapa .meta')!.textContent).toContain('Ritmo posterior');
|
||||
const id = root.querySelector<HTMLButtonElement>('tbody tr.tea-row button.patient-link')!;
|
||||
expect(id.textContent!.trim()).toBe('T-0001');
|
||||
id.click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
expect(ficha).toHaveBeenLastCalledWith(true);
|
||||
expect(root.querySelector('tr.tea-detalle')).toBeNull();
|
||||
const seccionFicha = root.querySelector('section.ficha-tea')!;
|
||||
expect(seccionFicha.querySelector('h2')!.textContent).toContain('T-0001');
|
||||
expect(seccionFicha.querySelectorAll('details.seccion').length).toBeGreaterThanOrEqual(4);
|
||||
expect(root.querySelector<HTMLElement>('form')!.closest('[hidden]')).not.toBeNull();
|
||||
Array.from(seccionFicha.querySelectorAll('button')).find(b => b.textContent!.includes('Volver a Seguimiento'))!.click(); fixture.detectChanges();
|
||||
expect(ficha).toHaveBeenLastCalledWith(false);
|
||||
expect(root.querySelector('section.ficha-tea')).toBeNull();
|
||||
expect(root.querySelector<HTMLElement>('form')!.closest('[hidden]')).toBeNull();
|
||||
expect(root.querySelectorAll('tbody tr.tea-row')).toHaveLength(2);
|
||||
http.verify();
|
||||
});
|
||||
it('el resumen completo son secciones con encabezado plegable, abiertas, y los reactivos van plegados dentro del ADOS-2', () => {
|
||||
const root: HTMLElement = resumen(detalle).nativeElement;
|
||||
const secciones = Array.from(root.querySelectorAll<HTMLDetailsElement>('details.seccion'));
|
||||
expect(secciones.map(d => d.querySelector('summary h2')!.textContent!.replace('Datos de ejemplo', '').trim())).toEqual(
|
||||
['Datos del paciente', 'ADOS-2', 'Calidad del EEG', 'Alteraciones del EEG']);
|
||||
expect(secciones.every(d => d.open)).toBe(true);
|
||||
expect(root.querySelector('.tarjetas, .panel')).toBeNull();
|
||||
expect(seccion(root, 'Datos del paciente').textContent).toContain('T-0001');
|
||||
expect(seccion(root, 'Datos del paciente').textContent).toContain('16-23 meses');
|
||||
const reactivos = seccion(root, 'ADOS-2').querySelector<HTMLDetailsElement>('details:not(.seccion)')!;
|
||||
expect(reactivos.open).toBe(false);
|
||||
expect(reactivos.textContent).toContain('A2 · Reactivo A2');
|
||||
secciones[1].open = false;
|
||||
expect(secciones[1].open).toBe(false);
|
||||
http.verify();
|
||||
});
|
||||
it('sin filtros no envía sus parámetros', () => {
|
||||
@@ -258,22 +300,24 @@ describe('Seguimiento TEA', () => {
|
||||
expect(toggles[1].getAttribute('aria-expanded')).toBe('true');
|
||||
http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges();
|
||||
const panel = root.querySelector('#tea-detalle-T-0002')!;
|
||||
// Four summary cards, two by two, with the verdicts and no maps or item tables.
|
||||
expect(Array.from(panel.querySelectorAll('.tarjetas > section')).map(c => c.getAttribute('aria-label'))).toEqual([
|
||||
'Resumen ADOS-2', 'Calidad del EEG', 'Alteraciones del EEG', 'Relación de las alteraciones del EEG con el ADOS-2']);
|
||||
expect(panel.textContent).toContain('CSS 3');
|
||||
expect(panel.textContent).toContain('Afecto social (AS)');
|
||||
expect(panel.textContent).toContain('Válido');
|
||||
// Opens with the map of the first altered metric.
|
||||
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
// Item scores start collapsed.
|
||||
expect(panel.querySelector<HTMLDetailsElement>('details')!.open).toBe(false);
|
||||
expect(panel.querySelector('app-plotly-chart')).toBeNull();
|
||||
expect(panel.querySelector('details')).toBeNull();
|
||||
const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!;
|
||||
expect(metricas.textContent).toContain('Datos de ejemplo');
|
||||
expect(metricas.textContent).toContain('1 de 4 métricas evaluadas fuera de la referencia');
|
||||
expect(metricas.textContent).toContain('Ritmo posterior');
|
||||
expect(metricas.textContent).toContain('Disminuido');
|
||||
expect(metricas.textContent).toContain('Posibles efectos asociados');
|
||||
expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.');
|
||||
expect(metricas.textContent).toContain('No se pudo medir en el estudio.');
|
||||
expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual(
|
||||
['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']);
|
||||
expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.');
|
||||
expect(metricas.textContent).not.toContain('Husos de sueño N3');
|
||||
expect(panel.querySelector('[aria-label="Calidad del EEG"]')!.textContent).toContain('1 de 2 reglas del estudio fuera de rango · 1 canal descartado');
|
||||
// The whole record opens in its own section from the patient id and from the cards' button.
|
||||
const enlace = panel.querySelector<HTMLButtonElement>('button.completo')!;
|
||||
expect(enlace.textContent).toContain('resumen completo');
|
||||
(root.querySelectorAll('tbody tr.tea-row')[2] as HTMLElement).click(); fixture.detectChanges();
|
||||
expect(root.querySelector('#tea-detalle-T-0002')).toBeNull();
|
||||
http.expectOne('/tea/seguimiento/T-0004').flush({ ...detalle, id_seudonimo: 'T-0004', ados2: null, eeg: null }); fixture.detectChanges();
|
||||
@@ -345,12 +389,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow();
|
||||
});
|
||||
it('la calidad es el veredicto del análisis, con sus reglas y los canales descartados, y se valida', () => {
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges();
|
||||
const panel = root.querySelector('section.calidad')!;
|
||||
const panel = seccion(resumen(detalle).nativeElement, 'Calidad del EEG');
|
||||
const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim();
|
||||
expect(texto(panel.querySelector('.css')!)).toBe('Válido');
|
||||
expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']);
|
||||
@@ -381,8 +420,8 @@ describe('Seguimiento TEA', () => {
|
||||
});
|
||||
// The association model's panel (prototype, simulated data): the field is optional and checked when present.
|
||||
it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => {
|
||||
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa',
|
||||
resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
|
||||
const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'CSS',
|
||||
resultado_etiqueta: 'Puntaje de severidad calibrado (CSS)', evento: '>=8', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002,
|
||||
probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 };
|
||||
const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 };
|
||||
const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } });
|
||||
@@ -392,12 +431,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow();
|
||||
expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow();
|
||||
const fixture = open();
|
||||
request().flush(tres); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelectorAll<HTMLButtonElement>('button.row-toggle')[0].click(); fixture.detectChanges();
|
||||
http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges();
|
||||
const filas = Array.from(root.querySelectorAll('section.relacion tbody tr'));
|
||||
const filas = Array.from(seccion(resumen(rel([otra, fila])).nativeElement, 'Relación con el ADOS-2').querySelectorAll('tbody tr'));
|
||||
expect(filas.length).toBe(1);
|
||||
expect(filas[0].classList.contains('alterada')).toBe(true);
|
||||
expect(filas[0].textContent).toContain('q < 0.001');
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
<header><h1>Trastorno del espectro autista</h1><p>Explora los indicadores de trastorno del espectro autista.</p></header>
|
||||
<nav class="domain-nav" aria-label="Dominios de indicadores"><a routerLink="/indicadores/cacu">Cáncer cervicouterino</a><a routerLink="/indicadores/cama">Cáncer de mama</a><a routerLink="/indicadores/tea" aria-current="page">Trastorno del espectro autista</a></nav>
|
||||
<nav class="tabs" aria-label="Secciones de trastorno del espectro autista">
|
||||
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Resumen</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Histórico</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Seguimiento</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'resumen' ? 'page' : null" (click)="changeSection('resumen')">Indicadores</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'historico' ? 'page' : null" (click)="changeSection('historico')">Trazabilidad</button>
|
||||
<button type="button" [attr.aria-current]="section() === 'seguimiento' ? 'page' : null" (click)="changeSection('seguimiento')">Análisis de Riesgo</button>
|
||||
</nav>
|
||||
@if (section() !== 'seguimiento') {
|
||||
<section aria-label="Consulta de indicadores">
|
||||
<h2>{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}</h2>
|
||||
<h2>{{ section() === 'resumen' ? 'Indicadores' : 'Trazabilidad' }}</h2>
|
||||
<form (ngSubmit)="section() === 'resumen' ? loadSummary() : loadHistory()">
|
||||
@if (section() === 'resumen') { <label>Periodo <input name="periodo" [(ngModel)]="periodo" required placeholder="2025-S1"></label> }
|
||||
@else {
|
||||
@@ -30,8 +30,8 @@
|
||||
}
|
||||
</section>
|
||||
}
|
||||
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Seguimiento">
|
||||
<h2>Seguimiento</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
|
||||
<section [hidden]="section() !== 'seguimiento' || selected() !== null" aria-label="Análisis de Riesgo">
|
||||
<h2>Análisis de Riesgo</h2><p>Consulte los episodios según la fecha de corte y los filtros seleccionados.</p>
|
||||
<form (ngSubmit)="applyFilters()" class="filters">
|
||||
<label>Desde <input type="date" name="desde" [(ngModel)]="filters.since"></label><label>Fecha de corte <input type="date" name="corte" [(ngModel)]="filters.cutoff"></label>
|
||||
<label>Estado <select name="status" [(ngModel)]="filters.status"><option value="">Todos</option><option value="active">En seguimiento</option><option value="finished">Finalizado</option></select></label>
|
||||
@@ -40,7 +40,7 @@
|
||||
<label>Edad al M-CHAT <select name="age" [(ngModel)]="filters.age"><option value="">Todas</option><option value="16_23">16 a 23 meses</option><option value="24_29">24 a 29 meses</option><option value="30_36">30 a 36 meses</option></select></label>
|
||||
<label>M-CHAT mínimo <input type="number" name="mchatMin" [(ngModel)]="filters.mchatMin"></label><label>M-CHAT máximo <input type="number" name="mchatMax" [(ngModel)]="filters.mchatMax"></label>
|
||||
<label>CSS mínimo <input type="number" name="cssMin" [(ngModel)]="filters.cssMin"></label><label>CSS máximo <input type="number" name="cssMax" [(ngModel)]="filters.cssMax"></label>
|
||||
<label>EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
|
||||
<label>Estatus de EEG <select name="eeg" [(ngModel)]="filters.eeg"><option value="">Todos</option>@if (alterationsAvailable()) { <option value="normal">Normal</option><option value="anormal">Anormal</option> } @else { <option value="valido">Con EEG válido</option> }<option value="sin-eeg-valido">Sin EEG válido</option></select></label>
|
||||
@if (alterationsAvailable() && alterationTypes().length) { <label>Alteración <select name="alteration" [(ngModel)]="filters.alteration"><option value="">Todas</option>@for (item of alterationTypes(); track item.code) { <option [value]="item.code">{{ item.display }}</option> }</select></label> }
|
||||
<button type="submit">Aplicar filtros</button>
|
||||
</form>
|
||||
@@ -56,7 +56,7 @@
|
||||
}
|
||||
</section>
|
||||
@if (section() === 'seguimiento' && selected()) {
|
||||
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Seguimiento</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
|
||||
<section aria-label="Ficha del paciente"><button type="button" (click)="back()">Volver a Análisis de Riesgo</button><h2>Ficha del paciente</h2><p>{{ selected() }}</p><p>La ficha muestra la información disponible a la fecha actual.</p>
|
||||
@if (patientState() === 'cargando') { <p role="status">Consultando ficha…</p> }
|
||||
@if (patientState() === 'error') { <p role="alert">{{ patientError() }}</p> }
|
||||
@if (patientState() === 'listo') {
|
||||
|
||||
@@ -17,8 +17,17 @@ describe('TEA FHIR journey', () => {
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/fhir/Measure').flush(bundle(measure));
|
||||
http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] });
|
||||
return { c, http };
|
||||
return { c, http, fixture };
|
||||
}
|
||||
it('presenta las etiquetas de las tres secciones en la vista de estatus', () => {
|
||||
const { fixture, http } = setup();
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.tabs button'), tab => tab.textContent?.trim()))
|
||||
.toEqual(['Indicadores', 'Trazabilidad', 'Análisis de Riesgo']);
|
||||
expect(root.querySelector('section[aria-label="Consulta de indicadores"] h2')?.textContent).toBe('Indicadores');
|
||||
http.verify();
|
||||
});
|
||||
it('distinguishes zero, missing and masked values and requests the historical periods', () => {
|
||||
const { c, http } = setup();
|
||||
expect(c.value({ count: 0 }, 'count')).toBe('0');
|
||||
|
||||
Reference in New Issue
Block a user