import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatDialog } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelect, MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } 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 { IndicadoresService } from './indicadores.service'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; type Panel = { item: Pick & { contrato?: Indicador['contrato'] }; rango?: string } & ( { estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; const CASOS = 'M28_casos_por_estado'; const PERSONALIZADO = -1; // CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not // publish is drawn as a pending panel instead of being left out, so what is missing stays visible. export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' }, { id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA }, { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, { id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' }, { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, ]; // 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[] { 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).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, 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]; }); } // Evolution of each indicator: the granularity and how many of the latest periods to show. // 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], template: `

Filtros

Intervalo de análisis @if (tipos().includes('mes')) { Mensual } @if (tipos().includes('semestre')) { Semestral }
Periodos a mostrar @for (opcion of opciones(); track opcion.valor) { {{ opcion.etiqueta }} } @if (ventana() === PERSONALIZADO) { }
@for (panel of paneles(); track panel.item.id) {

{{ panel.item.titulo }}

@if (panel.rango) {

{{ panel.rango }}

} @switch (panel.estado) { @case ('pendiente') {

Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.

} @case ('cargando') { } @case ('vacio') {

Sin reportes publicados para este intervalo de análisis.

} @case ('error') {

{{ panel.mensaje }}

} @case ('listo') { @if (panel.pasos; as pasos) {
@for (paso of pasos; track paso.titulo) {

{{ paso.titulo }}

}
} @else { } @if (panel.figura.comoLeer) {

{{ panel.figura.comoLeer }}

} @if (panel.figura.suprimidos.length) {
Datos suprimidos

Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}

} @if (panel.figura.sinDato.length) {
Periodos sin dato ({{ panel.figura.sinDato.length }})

Sin dato: {{ panel.figura.sinDato.join(', ') }}.

} } }
}
`, styles: ` @use '@angular/material' as mat; :host { display: block; min-width: 0; } .controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } .controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; } // Same field height as the summary filters. The theme also rewrites corners, which would turn the switch into a pill. .controles.compacto { @include mat.theme((density: -4)); --mat-sys-corner-extra-small: 2px; --mat-sys-corner-small: 2px; --mat-sys-corner-medium: 4px; --mat-sys-corner-large: 4px; --mat-sys-corner-extra-large: 6px; --mat-sys-corner-full: 4px; } .controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); } .interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; } .interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; } .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); 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 { 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; } .nota-pie summary { width: fit-content; cursor: pointer; } .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); } .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)); } } h3 { margin: 0; font: var(--mat-sys-title-small); } mat-form-field { flex: 0 1 14rem; min-width: 0; max-width: 24rem; } `, }) export class IndicadoresHistorico { readonly dominio = input.required(); readonly catalog = input.required(); readonly tema = input.required(); readonly active = input(false); // The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere. private readonly publicados = computed(() => this.dominio() === 'cama' ? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog()); // Only the granularities some indicator publishes; monthly first when there is one. readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo)))); readonly elegido = signal(undefined); readonly tipo = computed(() => { const elegido = this.elegido(), tipos = this.tipos(); return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes'; }); // How many of the latest periods to show, per granularity; 0 shows them all. private readonly ventanas = signal>>({}); readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0); readonly PERSONALIZADO = PERSONALIZADO; // The periods the user picked in the dialog, per granularity. private readonly personalizados = signal>>({}); private readonly dialogo = inject(MatDialog); private readonly selector = viewChild('selector'); // Every period published for the granularity by any indicator. private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {}) .flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : []))); // The periods on screen, out of those an indicator publishes. private recortar(periodos: readonly string[]) { const orden = cronologico(periodos), ventana = this.ventana(); if (ventana !== PERSONALIZADO) return ventana ? orden.slice(-ventana) : orden; const elegidos = this.personalizados()[this.tipo()] ?? []; return orden.filter(p => elegidos.includes(p)); } private readonly service = inject(IndicadoresService); private readonly periodos = inject(IndicadoresPeriodos); private readonly cargas = signal>>>({}); private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>(); private solicitada?: string; private catalogoCargado?: readonly Indicador[]; // Steps of five, up to what the indicator with the most periods has published. readonly opciones = computed(() => { const tipo = this.tipo(); const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0)); const opciones = []; for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` }); const elegidos = this.personalizados()[tipo]?.length; return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' }, ...(total ? [{ valor: PERSONALIZADO, etiqueta: elegidos && this.ventana() === PERSONALIZADO ? `Personalizado (${elegidos} ${unidad(tipo, elegidos)})` : 'Personalizado…' }] : [])]; }); readonly paneles = computed(() => { const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(); // Top of the shared scale: the highest third quartile of the steps, in the periods on screen. const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => { const carga = cargas?.[id]; if (carga?.estado !== 'listo') return []; 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 } => { if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' }; const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; if (carga.estado !== 'listo') return { item, ...carga }; const periodos = this.recortar(carga.datos.periodos); if (!periodos.length) return { item, estado: 'vacio' }; const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) }; const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`; const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`; try { return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos }; } catch (error) { return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; } }; if (this.dominio() === 'cama') { if (!this.publicados().length) return []; return HISTORICO_CAMA.map((entrada): Panel => { const item = this.catalog().find(i => i.id === entrada.id); return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' }; }); } return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema); }); constructor() { this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo)) .map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))), takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => { this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) })); }); effect(() => { const tipo = this.tipo(), items = this.publicados(); if (!this.active() || !items.length) return; untracked(() => { if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; } if (this.cargas()[tipo] || this.solicitada === tipo) return; this.solicitada = tipo; this.solicitudes.next({ tipo, items }); }); }); } private cargar(item: Indicador, tipo: TipoPeriodo): Observable { return this.periodos.periodos(this.dominio(), item.id).pipe( map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)), switchMap((periodos): Observable => periodos.length ? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos }))) : of({ estado: 'vacio' })), catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); } elegirVentana(valor: number) { if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; } this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); } abrirPersonalizado() { const tipo = this.tipo(), periodos = this.disponibles(); // Starts from what's on screen, so the user only adjusts it. const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos; const data: PeriodosDialogoDatos = { tipo, periodos, elegidos }; this.dialogo.open(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' }) .afterClosed().subscribe(resultado => { if (resultado?.length) { this.personalizados.update(actual => ({ ...actual, [tipo]: resultado })); this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO })); } // Cancelled, the selector goes back to what's on screen. this.selector()?.writeValue(this.ventana()); }); } reintentar() { const tipo = this.tipo(); this.solicitada = tipo; this.cargas.update(({ [tipo]: _, ...resto }) => resto); this.solicitudes.next({ tipo, items: this.publicados() }); } }