093ceffa36
The tab has the same name in every domain, and the texts that point to it (patient lists opened from the analysis, the patient file error) use it.
252 lines
17 KiB
TypeScript
252 lines
17 KiB
TypeScript
import { Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, untracked } from '@angular/core';
|
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
import { HttpErrorResponse } from '@angular/common/http';
|
|
import { FormsModule } from '@angular/forms';
|
|
import { MatButtonModule } from '@angular/material/button';
|
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
|
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
import { IndicadorKpiCard } from './indicador-kpi-card';
|
|
import { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
|
|
import { isoDate } from './cacu-seguimiento.models';
|
|
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
|
|
import { etiquetaBirads } from './etiquetas-cohorte';
|
|
import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service';
|
|
import { Dominio, Tema } from './indicadores.models';
|
|
|
|
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
|
|
|
|
/**
|
|
* The patients behind a group of the aggregate, for the page to open them in Seguimiento: the list's filters, how to
|
|
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
|
|
* patients the analysis counts there.
|
|
*/
|
|
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
|
|
|
|
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
|
|
|
|
export { hoyIso };
|
|
|
|
/** Why a group cannot open its patients, or nothing when it can: only a published group does. */
|
|
export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined {
|
|
const g = agregado.grupos.find(x => x.codigo === codigo);
|
|
return !g || g.suprimido ? MOTIVO_GRUPO_SUPRIMIDO : undefined;
|
|
}
|
|
|
|
/** The selection of a published group: the whole group of the cohort at the cut-off it was counted at, nothing else. */
|
|
export function seleccionDeGrupo(agregado: AnalisisAgregado, codigo: string): SeleccionPacientes | undefined {
|
|
const g = agregado.grupos.find(x => x.codigo === codigo);
|
|
if (!g || motivoSinLista(agregado, codigo)) return undefined;
|
|
return { filtros: { birads: codigo }, etiqueta: `Categoría BI-RADS: ${etiquetaBirads(codigo)}`, corte: agregado.corte, esperados: g.n,
|
|
contexto: { cohorte: agregado.cohorte, escenario: agregado.escenario, revision: agregado.revision } };
|
|
}
|
|
|
|
/** The scrolling ancestor of an element, or the document's own scroller. */
|
|
function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
|
for (let n = el.parentElement; n; n = n.parentElement) {
|
|
const overflow = getComputedStyle(n).overflowY;
|
|
if ((overflow === 'auto' || overflow === 'scroll') && n.scrollHeight > n.clientHeight) return n;
|
|
}
|
|
return (el.ownerDocument.scrollingElement ?? el.ownerDocument.documentElement) as HTMLElement;
|
|
}
|
|
|
|
// Epidemiological analysis of the breast cohort. For now: how many patients of the cohort are in each BI-RADS category at
|
|
// a cut-off, as a count (not an incidence or a survival estimate). A published category opens its patients in Seguimiento;
|
|
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
|
|
@Component({
|
|
selector: 'app-indicadores-analisis',
|
|
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
|
|
template: `
|
|
<section class="analisis" aria-labelledby="analisis-titulo">
|
|
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
|
|
<p class="nota">Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.</p>
|
|
@if (datos(); as d) {
|
|
<p class="contexto">Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.</p>
|
|
<div class="tarjetas">
|
|
<app-indicador-kpi-card title="Categorías publicadas" [value]="publicadas()" state="Disponible" [quietWhenAvailable]="true"
|
|
[additionalInfo]="'de ' + d.grupos.length + ' categorías BI-RADS.'" />
|
|
<app-indicador-kpi-card title="Categorías no publicadas" [value]="d.grupos.length - publicadas()" state="Disponible" [quietWhenAvailable]="true"
|
|
[additionalInfo]="'Con menos de ' + d.umbral_supresion + ' pacientes: su conteo y su lista no se publican.'" />
|
|
</div>
|
|
}
|
|
<form class="controles" (ngSubmit)="consultar()">
|
|
<label>Fecha de corte <input name="corte" type="date" required [(ngModel)]="corte" [max]="hoy" /></label>
|
|
<button type="submit" mat-stroked-button [disabled]="carga().estado === 'cargando'">Consultar</button>
|
|
</form>
|
|
<article class="panel" aria-labelledby="birads-titulo">
|
|
<h3 id="birads-titulo">Pacientes por categoría BI-RADS</h3>
|
|
@switch (carga().estado) {
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Consultando el análisis" /> }
|
|
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
|
|
@case ('no-disponible') {
|
|
<p role="status">La cohorte no está disponible en este momento.</p>
|
|
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
|
}
|
|
@case ('error') {
|
|
<div role="alert"><p>{{ $any(carga()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
|
}
|
|
}
|
|
@if (datos(); as d) {
|
|
@if (todasSuprimidas()) {
|
|
<p class="nota">Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.</p>
|
|
}
|
|
<p class="aviso" role="status">{{ aviso() }}</p>
|
|
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
|
|
label="Pacientes por categoría BI-RADS" />
|
|
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Análisis de riesgos. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
|
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
|
|
<table>
|
|
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
|
|
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
|
<tbody>
|
|
@for (g of d.grupos; track g.codigo) {
|
|
<tr [attr.data-grupo]="g.codigo">
|
|
<th scope="row">{{ etiqueta(g.codigo) }}</th>
|
|
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
|
|
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
|
|
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Análisis de riesgos'">Ver pacientes</button> }</td>
|
|
</tr>
|
|
}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
}
|
|
</article>
|
|
</section>
|
|
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
|
|
`,
|
|
styles: `
|
|
:host { display: block; min-width: 0; }
|
|
/* Positioned so the absolutely placed visually-hidden labels belong to this view: otherwise they are laid out against the document and give it a vertical scroll of its own. */
|
|
.analisis { position: relative; display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
|
|
.analisis > * { margin: 0; }
|
|
/* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */
|
|
:host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); }
|
|
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); }
|
|
@media (min-width: 700px) { .tarjetas { 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);
|
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
|
h2, h3 { margin: 0; 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; }
|
|
.nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
|
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-4); background: var(--issste-surface);
|
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
|
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
|
input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; }
|
|
input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
|
/* The live region stays in the page, so what is written into it is announced; empty, it takes no room. */
|
|
.aviso { padding: var(--issste-space-2) var(--issste-space-3); border-left: 4px solid var(--issste-accent); font: var(--mat-sys-body-medium); }
|
|
.aviso:empty { padding: 0; border: 0; margin: 0; }
|
|
app-plotly-chart { margin-top: var(--issste-space-3); }
|
|
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
|
|
.tabla-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
|
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
|
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
|
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
|
td:nth-child(2) { font-variant-numeric: tabular-nums; }
|
|
td:last-child { min-width: 11rem; }
|
|
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
|
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
|
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
|
@media (max-width: 600px) { .panel { padding: var(--issste-space-4); } .controles label, .controles input { width: 100%; } }
|
|
`,
|
|
})
|
|
export class IndicadoresAnalisis {
|
|
readonly dominio = input.required<Dominio>();
|
|
readonly tema = input.required<Tema>();
|
|
readonly active = input(false);
|
|
// The patients of a group, for the page to open them in Seguimiento.
|
|
readonly verPacientes = output<SeleccionPacientes>();
|
|
readonly miles = (v: number) => v.toLocaleString('es-MX');
|
|
readonly etiqueta = etiquetaBirads;
|
|
readonly motivo = MOTIVO_GRUPO_SUPRIMIDO;
|
|
readonly hoy = hoyIso();
|
|
private readonly service = inject(AnalisisService);
|
|
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
|
private readonly pedidos = new Subject<string>();
|
|
private abierto = false;
|
|
private ultimo?: string;
|
|
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
|
|
corte = this.hoy;
|
|
// The cut-off of the last query: the descriptive sections follow it.
|
|
readonly corteConsultado = signal(this.hoy);
|
|
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
|
|
// Why the last click on a bar opened nothing.
|
|
readonly aviso = signal('');
|
|
readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; });
|
|
// How many categories the answer publishes; the rest are suppressed. Counts categories only, never patients.
|
|
readonly publicadas = computed(() => this.datos()?.grupos.filter(g => !g.suprimido).length ?? 0);
|
|
// The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published.
|
|
readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido));
|
|
readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; });
|
|
|
|
constructor() {
|
|
const destroy = inject(DestroyRef);
|
|
const cargar = (corte: string): Observable<Carga<AnalisisAgregado>> => {
|
|
let fuente: Observable<AnalisisAgregado>;
|
|
try { fuente = this.service.agregado(this.dominio(), corte); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); }
|
|
return fuente.pipe(
|
|
map((datos): Carga<AnalisisAgregado> => ({ estado: 'listo', datos })),
|
|
catchError(error => of(this.fallo(error))),
|
|
startWith<Carga<AnalisisAgregado>>({ estado: 'cargando' }));
|
|
};
|
|
this.pedidos.pipe(switchMap(cargar), takeUntilDestroyed(destroy)).subscribe(c => { this.aviso.set(''); this.carga.set(c); });
|
|
effect(() => {
|
|
if (!this.active() || this.abierto) return;
|
|
untracked(() => { this.abierto = true; this.consultar(); });
|
|
});
|
|
}
|
|
|
|
private fallo(error: unknown): Carga<AnalisisAgregado> {
|
|
if (error instanceof HttpErrorResponse) {
|
|
if (error.status === 404) return { estado: 'pendiente' };
|
|
if (error.status === 503) return { estado: 'no-disponible' };
|
|
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
|
|
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la fecha de corte. Revisa la fecha.' };
|
|
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
|
|
}
|
|
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
|
|
}
|
|
consultar() {
|
|
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
|
|
this.ultimo = this.corte;
|
|
this.corteConsultado.set(this.corte);
|
|
this.pedidos.next(this.corte);
|
|
}
|
|
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
|
|
|
|
// A click on a published bar is the same as its «Ver pacientes» button; a suppressed bar does nothing.
|
|
clicGrupo(evento: unknown) {
|
|
const codigo = grupoDelClic(evento, this.datos());
|
|
if (!codigo) return;
|
|
const fila = Array.from(this.host.nativeElement.querySelectorAll<HTMLElement>('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo);
|
|
this.verGrupo(codigo, fila?.querySelector<HTMLElement>('button.ver') ?? this.host.nativeElement.querySelector<HTMLElement>('.plot-viewport'));
|
|
}
|
|
// The patients of a published group: the page opens them in Seguimiento. Where the user was is kept for the way back.
|
|
verGrupo(codigo: string, origen?: EventTarget | null) {
|
|
const d = this.datos();
|
|
if (!d) return;
|
|
this.aviso.set(motivoSinLista(d, codigo) ?? '');
|
|
const seleccion = seleccionDeGrupo(d, codigo);
|
|
if (!seleccion) return;
|
|
const el = origen instanceof HTMLElement ? origen : null;
|
|
const area = contenedorDeScroll(this.host.nativeElement);
|
|
this.retorno = { origen: el, area, arriba: area.scrollTop };
|
|
this.verPacientes.emit(seleccion);
|
|
}
|
|
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
|
|
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
|
|
const area = contenedorDeScroll(this.host.nativeElement);
|
|
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
|
|
this.verPacientes.emit(evento.seleccion);
|
|
}
|
|
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
|
|
restaurar() {
|
|
const r = this.retorno;
|
|
if (!r) return;
|
|
if (r.area.isConnected) r.area.scrollTop = r.arriba;
|
|
(r.origen?.isConnected ? r.origen : this.host.nativeElement.querySelector<HTMLElement>('input[name="corte"]'))?.focus({ preventScroll: true });
|
|
this.retorno = undefined;
|
|
}
|
|
}
|