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 = { 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; 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: `

Análisis epidemiológico

Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.

@if (datos(); as d) {

Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.

}

Pacientes por categoría BI-RADS

@switch (carga().estado) { @case ('cargando') { } @case ('pendiente') {

Funcionalidad pendiente de publicación.

} @case ('no-disponible') {

La cohorte no está disponible en este momento.

} @case ('error') {

{{ $any(carga()).mensaje }}

} } @if (datos(); as d) { @if (todasSuprimidas()) {

Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.

}

{{ aviso() }}

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.

@for (g of d.grupos; track g.codigo) { }
Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}
CategoríaPacientesAnálisis de riesgos
{{ etiqueta(g.codigo) }} {{ g.suprimido ? 'No publicado' : miles(g.n!) }} @if (g.suprimido) { {{ motivo }} } @else { }
}
`, 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(); readonly tema = input.required(); readonly active = input(false); // The patients of a group, for the page to open them in Seguimiento. readonly verPacientes = output(); 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); private readonly pedidos = new Subject(); 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>({ 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> => { let fuente: Observable; 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 => ({ estado: 'listo', datos })), catchError(error => of(this.fallo(error))), startWith>({ 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 { 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('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo); this.verGrupo(codigo, fila?.querySelector('button.ver') ?? this.host.nativeElement.querySelector('.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('input[name="corte"]'))?.focus({ preventScroll: true }); this.retorno = undefined; } }