47a0ab5f1b
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
369 lines
29 KiB
TypeScript
369 lines
29 KiB
TypeScript
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
|
|
import { HttpErrorResponse } from '@angular/common/http';
|
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
import { FormsModule } from '@angular/forms';
|
|
import { MatButtonModule } from '@angular/material/button';
|
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
|
import { Observable, Subscription } from 'rxjs';
|
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
import { IndicadorKpiCard } from './indicador-kpi-card';
|
|
import {
|
|
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
|
|
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
|
|
} from './indicadores-analisis.service';
|
|
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
|
|
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
|
|
import type { SeleccionPacientes } from './indicadores-analisis';
|
|
|
|
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
|
|
const VACIA = { data: [], layout: {} } as PlotlyFigure;
|
|
const miles = (v: number) => v.toLocaleString('es-MX');
|
|
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
|
|
|
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
|
|
export function valorTarjeta(t: TarjetaAnalisis): string | null {
|
|
if (t.estado !== 'disponible' || t.valor === null) return null;
|
|
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
|
|
}
|
|
export function detalleTarjeta(t: TarjetaAnalisis): string {
|
|
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
|
|
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
|
|
const partes: string[] = [];
|
|
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
|
|
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
|
|
partes.push(t.descripcion);
|
|
return partes.join(' ');
|
|
}
|
|
|
|
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
|
|
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
|
|
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
|
|
@Component({
|
|
selector: 'app-indicadores-analisis-descriptivo',
|
|
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
|
|
template: `
|
|
<section class="bloque" aria-labelledby="desc-resumen">
|
|
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
|
|
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
|
|
<form class="controles" (ngSubmit)="aplicar()">
|
|
<label>Ventana
|
|
<select name="meses" [(ngModel)]="meses">
|
|
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
|
|
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
|
|
</select></label>
|
|
<label>Categoría BI-RADS
|
|
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
|
|
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
|
|
<label>Grupo de edad
|
|
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
|
|
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
|
|
<label>Horizonte del seguimiento diagnóstico
|
|
<select name="horizonte" [(ngModel)]="horizonte">
|
|
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
|
|
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
|
|
</form>
|
|
@switch (resumen().estado) {
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
|
|
@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)="aplicar()">Reintentar consulta</button> }
|
|
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
|
|
}
|
|
@if (r(); as res) {
|
|
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
|
|
<div class="tarjetas">
|
|
@for (t of res.indicadores; track t.clave) {
|
|
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
|
|
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
|
|
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
|
|
}
|
|
</div>
|
|
}
|
|
</section>
|
|
|
|
<section class="bloque" aria-labelledby="desc-dist">
|
|
<h2 id="desc-dist">Distribución de pacientes</h2>
|
|
<div class="selector" role="group" aria-label="Distribuir por">
|
|
@for (d of dimensionesDist; track d.clave) {
|
|
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
|
|
}
|
|
</div>
|
|
@switch (distribucion().estado) {
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
|
|
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
|
|
}
|
|
@if (dist(); as d) {
|
|
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
|
|
@else {
|
|
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
|
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
|
|
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
|
|
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
|
<tbody>@for (i of d.items; track i.codigo) {
|
|
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
|
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
|
|
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
|
|
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
|
|
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
|
|
}</tbody></table>
|
|
</div>
|
|
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
|
|
}
|
|
}
|
|
</section>
|
|
|
|
<section class="bloque" aria-labelledby="desc-comp">
|
|
<h2 id="desc-comp">Comparación entre grupos</h2>
|
|
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
|
|
<div class="controles">
|
|
<label>Comparar por
|
|
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
|
|
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
|
|
<label>Resultado
|
|
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
|
|
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
|
|
</div>
|
|
@switch (comparacion().estado) {
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
|
|
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
|
|
}
|
|
@if (comp(); as c) {
|
|
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
|
|
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
|
|
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
|
|
<table><caption>{{ c.denominador }}</caption>
|
|
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
|
|
<tbody>@for (g of c.grupos; track g.codigo) {
|
|
<tr><th scope="row">{{ g.etiqueta }}</th>
|
|
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
|
|
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
|
|
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
|
|
}</tbody></table>
|
|
</div>
|
|
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
|
|
}
|
|
</section>
|
|
|
|
<section class="bloque" aria-labelledby="desc-mapa">
|
|
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
|
|
<div class="selector" role="group" aria-label="Medida del mapa">
|
|
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
|
|
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
|
|
</div>
|
|
@switch (mapa().estado) {
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
|
|
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
|
|
}
|
|
@if (m(); as mm) {
|
|
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
|
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
|
|
<details><summary>Valores publicados</summary>
|
|
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
|
|
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
|
|
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
|
|
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
|
|
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
|
|
}</tbody></table>
|
|
</div>
|
|
</details>
|
|
}
|
|
</section>
|
|
|
|
<section class="bloque" aria-labelledby="desc-tend">
|
|
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
|
|
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
|
|
<div class="controles">
|
|
<label>Periodo
|
|
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
|
|
<label>Periodos a mostrar
|
|
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
|
|
</div>
|
|
@switch (tendencia().estado) {
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
|
|
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
|
|
}
|
|
@if (t(); as tt) {
|
|
<div class="par">
|
|
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
|
|
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
|
|
</div>
|
|
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
|
|
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
|
|
<tbody>@for (p of tt.periodos; track p.periodo) {
|
|
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
|
|
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
|
|
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
|
|
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
|
|
}</tbody></table>
|
|
</div>
|
|
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
|
|
}
|
|
</section>
|
|
|
|
@if (r(); as res) {
|
|
<section class="bloque" aria-labelledby="desc-no">
|
|
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
|
|
<details class="plegable" data-plegable="no-disponibles">
|
|
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
|
|
<ul class="no-disponibles">
|
|
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
|
|
</ul>
|
|
</details>
|
|
</section>
|
|
}
|
|
`,
|
|
styles: `
|
|
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
|
|
.bloque { 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; }
|
|
p, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
|
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
|
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
|
|
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
|
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
|
|
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
|
|
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
|
|
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
|
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
|
|
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
|
app-plotly-chart { margin-top: var(--issste-space-3); }
|
|
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
|
|
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 { font-variant-numeric: tabular-nums; }
|
|
.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 currentColor; outline-offset: 2px; }
|
|
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
|
|
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
|
|
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
|
|
.plegable > summary h2 { display: inline; }
|
|
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
|
.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; }
|
|
`,
|
|
})
|
|
export class IndicadoresAnalisisDescriptivo {
|
|
readonly dominio = input.required<Dominio>();
|
|
readonly tema = input.required<Tema>();
|
|
readonly corte = input.required<string>();
|
|
readonly active = input(false);
|
|
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
|
|
readonly miles = miles; readonly decimal = decimal;
|
|
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
|
|
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
|
|
|
|
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
|
|
readonly por = signal('birads');
|
|
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
|
|
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
|
|
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
|
|
|
|
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
|
|
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
|
|
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
|
|
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
|
|
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
|
|
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
|
|
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
|
|
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
|
|
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
|
|
private readonly service = inject(AnalisisDescriptivoService);
|
|
private readonly destroy = inject(DestroyRef);
|
|
private readonly suscripciones = new Map<string, Subscription>();
|
|
private abierto = false; private corteCargado = ''; private tendCorte = '';
|
|
// The filters and window the sections were last asked with: one selection for all of them.
|
|
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
|
|
|
|
constructor() {
|
|
effect(() => {
|
|
const activa = this.active(), corte = this.corte();
|
|
if (!activa) return;
|
|
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
|
|
});
|
|
}
|
|
|
|
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
|
|
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
|
|
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
|
|
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
|
|
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
|
|
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
|
|
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
|
|
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
|
|
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
|
|
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
|
|
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
|
|
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
|
|
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
|
|
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
|
|
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
|
|
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
|
|
}
|
|
|
|
private pedido(): PedidoDescriptivo {
|
|
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
|
|
}
|
|
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
|
|
aplicar() {
|
|
this.pedidoVigente = this.pedido();
|
|
const p = this.pedidoVigente;
|
|
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
|
|
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
|
|
this.recargarDist(); this.recargarComp(); this.recargarMapa();
|
|
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
|
|
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
|
|
}
|
|
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
|
|
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
|
|
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
|
|
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
|
|
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
|
|
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
|
|
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
|
|
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
|
|
|
|
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
|
|
this.suscripciones.get(clave)?.unsubscribe();
|
|
destino.set({ estado: 'cargando' });
|
|
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
|
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
|
|
error: error => destino.set(this.fallo(error)),
|
|
}));
|
|
}
|
|
private fallo(error: unknown): Carga<never> {
|
|
if (error instanceof HttpErrorResponse) {
|
|
if (error.status === 404) return { estado: 'pendiente' };
|
|
if (error.status === 503) return { estado: 'no-disponible' };
|
|
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
|
|
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
|
|
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
|
|
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 >= 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.' };
|
|
}
|
|
|
|
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
|
|
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
|
|
if (!n) return;
|
|
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
|
|
this.verPacientes.emit({
|
|
origen: origen instanceof HTMLElement ? origen : null,
|
|
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
|
|
});
|
|
}
|
|
clicDist(evento: unknown) {
|
|
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
|
|
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
|
|
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
|
|
}
|
|
clicMapa(evento: unknown) {
|
|
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
|
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
|
|
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
|
|
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
|
|
}
|
|
}
|