import { Component, computed, DestroyRef, effect, inject, input, output, 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 { defer, map, Subscription } from 'rxjs'; import { IndicadorAyuda } from './indicador-ayuda'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; 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, 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 }; const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); interface Carga { disponibles?: string[]; datos?: IndicadorDatos; errorPeriodos?: string; consultados: ReadonlySet; enCurso: ReadonlySet; fallos: ReadonlyMap; } type Panel = { item: Pick & { contrato?: Indicador['contrato'] }; rango?: string; mensaje?: string } & ( { estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); class ContratoHistoricoInvalido extends Error {} const TIEMPOS = TEA_FIGURAS_OPORTUNIDAD; const TITULOS_TEA: Readonly> = { 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))); const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'].filter(r => nuevos.has(r.periodo)) : [])]; const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) }; return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(f => nuevos.has(f['periodo'] as string))], ...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) }; } // 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).figura })); const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))]; 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 []; return [panel]; }); } interface SerieResaltable { nombre: string; color: string } const nombreDe = (trazo: Record) => typeof trazo['name'] === 'string' ? trazo['name'] : ''; // Bands are drawn with their line: they are not series of their own. const esBanda = (trazo: Record) => trazo['fill'] === 'toself'; function colorDe(trazo: Record): 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, ...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); } // 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, IndicadorAyuda], 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) {
@if (dominio() === 'tea' && panel.estado === 'listo' && panel.figura.comoLeer) {

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

}

{{ panel.item.titulo }}

@if (panel.rango) {

{{ panel.rango }}

} @if (panel.mensaje) {

Error. {{ panel.mensaje }}

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

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

} @case ('desarrollo') {

Trabajo en desarrollo

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

{{ dominio() === 'cacu' ? 'Sin datos' : 'Sin reportes publicados para este intervalo de análisis.' }}

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

{{ paso.titulo }}

}
} @else { @if (series(panel); as lista) { @if (dominio() === 'tea' && lista.length > 1) {
@for (serie of lista; track serie.nombre) { }
} } } @if (panel.figura.comoLeer && dominio() !== 'tea') {

{{ 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 { 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; 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; } .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); } 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)); } } 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(); // The series each panel's chart draws, which a chip can highlight; one selection per panel. readonly resaltados = signal>>({}); 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>>(() => { 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 tema = input.required(); readonly active = input(false); readonly catalogLoading = input(false); readonly catalogError = input(''); readonly retryCatalog = output(); 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; // the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes. private readonly publicados = computed(() => { const config = this.config(); return config ? config.paneles.filter(entrada => !entrada.enDesarrollo).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>>({}); // Until the user picks one, the domain's initial window (when it declares one and there are more periods) or all. readonly ventana = computed(() => { const elegida = this.ventanas()[this.tipo()]; if (elegida !== undefined) return elegida; const inicial = this.config()?.periodosIniciales ?? 0, total = this.totalDisponibles(); return inicial && (!total || total > inicial) ? inicial : 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([...new Set(Object.values(this.cargas()[this.tipo()] ?? {}) .flatMap(carga => this.config()?.periodosIniciales ? carga.disponibles ?? [] : carga.datos?.periodos ?? []))])); private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {}) .map(carga => (this.config()?.periodosIniciales ? carga.disponibles : carga.datos?.periodos)?.length ?? 0))); // 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 peticiones = new Subscription(); private ambito?: { dominio: Dominio; catalogo: 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 = this.totalDisponibles(); 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?.datos) 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 => { if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' }; const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; const necesarios = this.necesarios(carga.disponibles ?? [], tipo); const mensaje = carga.errorPeriodos ?? necesarios.map(p => carga.fallos.get(p)).find(Boolean); const periodos = this.config()?.periodosIniciales ? necesarios.filter(p => carga.datos?.periodos.includes(p)) : this.recortar(carga.datos?.periodos ?? []); if (!periodos.length || !carga.datos) { if (mensaje) return { item, estado: 'error', mensaje }; return { item, estado: !carga.disponibles || necesarios.some(p => carga.enCurso.has(p)) ? 'cargando' : '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 { const propias = this.config(); const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), ...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) }; const figura = historicoFigura(datos, tema, opciones); if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) { return { item, estado: mensaje ? 'error' : 'vacio', 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' }; } }; const config = this.config(); if (config) { const cacu = this.dominio() === 'cacu'; if (!cacu && !this.publicados().length) return []; return config.paneles.map((entrada: PanelHistorico): Panel => { const visible = { id: entrada.id, titulo: entrada.titulo }; if (entrada.enDesarrollo) return { item: visible, estado: 'desarrollo' }; if (cacu && this.catalogError()) return { item: visible, estado: 'error', mensaje: this.catalogError() }; if (cacu && this.catalogLoading()) return { item: visible, estado: 'cargando' }; const item = this.catalog().find(i => i.id === entrada.id); if (!item) return { item: visible, estado: cacu ? 'desarrollo' : 'pendiente' }; return { ...panelDe(item), item: { ...visible, contrato: item.contrato } }; }); } 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() { this.destruccion.onDestroy(() => this.peticiones.unsubscribe()); effect(() => { const dominio = this.dominio(), catalogo = this.catalog(), tipo = this.tipo(); const activo = this.active() && !this.catalogLoading() && !this.catalogError(); untracked(() => { if (this.ambito?.catalogo !== catalogo || this.ambito?.dominio !== dominio) { this.peticiones.unsubscribe(); this.peticiones = new Subscription(); this.cargas.set({}); this.ambito = { dominio, catalogo }; } if (activo) this.cargarVentana(tipo); }); }); } private necesarios(disponibles: readonly string[], tipo: TipoPeriodo): string[] { if (!this.config()?.periodosIniciales) return [...disponibles]; const orden = cronologico(disponibles), ventana = this.ventanas()[tipo] ?? this.config()?.periodosIniciales; if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[tipo] ?? []).includes(p)); return ventana ? orden.slice(-ventana) : orden; } private guardarCarga(tipo: TipoPeriodo, id: string, carga: Carga) { this.cargas.update(actual => ({ ...actual, [tipo]: { ...actual[tipo], [id]: carga } })); } private cargarVentana(tipo: TipoPeriodo) { if (!this.active() || this.catalogLoading() || this.catalogError()) return; for (const { id, tipos_periodo } of this.publicados()) { if (!tipos_periodo.includes(tipo)) continue; const carga = this.cargas()[tipo]?.[id]; if (carga) this.solicitarPeriodos(tipo, id, carga); else this.descubrirPeriodos(tipo, id); } } private descubrirPeriodos(tipo: TipoPeriodo, id: string) { const carga: Carga = { consultados: new Set(), enCurso: new Set(), fallos: new Map() }; this.guardarCarga(tipo, id, carga); this.peticiones.add(defer(() => this.periodos.periodos(this.dominio(), id)).subscribe({ next: periodos => { const descubierta = { ...carga, disponibles: [...new Set(periodos.filter(p => p.tipo === tipo).map(p => p.periodo))] }; this.guardarCarga(tipo, id, descubierta); if (this.active() && this.tipo() === tipo) this.solicitarPeriodos(tipo, id, descubierta); }, error: error => this.guardarCarga(tipo, id, { ...carga, errorPeriodos: httpMessage(error) }), })); } private solicitarPeriodos(tipo: TipoPeriodo, id: string, carga: Carga) { if (!carga.disponibles) return; const faltan = this.necesarios(carga.disponibles, tipo) .filter(p => !carga.consultados.has(p) && !carga.enCurso.has(p) && !carga.fallos.has(p)); if (!faltan.length) return; this.guardarCarga(tipo, id, { ...carga, enCurso: new Set([...carga.enCurso, ...faltan]) }); const solicitados = new Set(faltan); const vigente = () => { const actual = this.cargas()[tipo]![id]; return { ...actual, enCurso: new Set([...actual.enCurso].filter(p => !solicitados.has(p))) }; }; const config = this.config(); const esperado = config?.paneles.find(panel => panel.id === id)?.contrato; this.peticiones.add(defer(() => this.service.datos(this.dominio(), id, tipo, faltan)).pipe(map(datos => { if (esperado && datos.contrato !== esperado) { throw new ContratoHistoricoInvalido(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`); } // Validate each batch before it is allowed to affect a series that already has valid periods. if (esperado && datos.periodos.length) historicoFigura(datos, this.tema(), config); return datos; })).subscribe({ next: datos => { const actual = vigente(); this.guardarCarga(tipo, id, { ...actual, consultados: new Set([...actual.consultados, ...faltan]), datos: actual.datos ? unir(actual.datos, datos) : datos }); }, error: error => { const actual = vigente(), fallos = new Map(actual.fallos); const mensaje = error instanceof ContratoHistoricoInvalido ? error.message : httpMessage(error); for (const periodo of faltan) fallos.set(periodo, mensaje); this.guardarCarga(tipo, id, { ...actual, fallos }); }, })); } private readonly destruccion = inject(DestroyRef); elegirVentana(valor: number) { if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; } this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); this.cargarVentana(this.tipo()); } 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().pipe(takeUntilDestroyed(this.destruccion)).subscribe(resultado => { if (resultado?.length) { this.personalizados.update(actual => ({ ...actual, [tipo]: resultado })); this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO })); if (this.tipo() === tipo) this.cargarVentana(tipo); } // Cancelled, the selector goes back to what's on screen. this.selector()?.writeValue(this.ventana()); }); } reintentar(id: string) { if (this.catalogError()) { this.retryCatalog.emit(); return; } const tipo = this.tipo(); const carga = this.cargas()[tipo]?.[id]; if (!carga) return; if (carga.errorPeriodos) { this.descubrirPeriodos(tipo, id); return; } const seleccion = this.necesarios(carga.disponibles ?? [], tipo); if (!seleccion.some(periodo => carga.fallos.has(periodo))) { // A figure can fail after its reports were accepted. Reload just that panel. if (!carga.enCurso.size) this.descubrirPeriodos(tipo, id); return; } const fallos = new Map(carga.fallos); for (const periodo of seleccion) fallos.delete(periodo); const corregida = { ...carga, fallos }; this.guardarCarga(tipo, id, corregida); this.solicitarPeriodos(tipo, id, corregida); } }