507 lines
30 KiB
TypeScript
507 lines
30 KiB
TypeScript
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<string>;
|
|
enCurso: ReadonlySet<string>;
|
|
fallos: ReadonlyMap<string, string>;
|
|
}
|
|
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { 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<Record<string, string>> = {
|
|
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<Panel, { estado: 'listo' }>).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<string, unknown>) => typeof trazo['name'] === 'string' ? trazo['name'] : '';
|
|
// Bands are drawn with their line: they are not series of their own.
|
|
const esBanda = (trazo: Record<string, unknown>) => trazo['fill'] === 'toself';
|
|
function colorDe(trazo: Record<string, unknown>): 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: `
|
|
<div class="controles compacto">
|
|
<h2>Filtros</h2>
|
|
<div class="controles-fila">
|
|
<div class="interval">
|
|
<span id="historico-intervalo" class="field-label">Intervalo de análisis</span>
|
|
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
|
|
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
|
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
|
</mat-button-toggle-group>
|
|
</div>
|
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
|
<mat-label>Periodos a mostrar</mat-label>
|
|
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
|
|
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
|
|
</mat-select>
|
|
</mat-form-field>
|
|
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
|
|
</div>
|
|
</div>
|
|
<div class="paneles">
|
|
@for (panel of paneles(); track panel.item.id) {
|
|
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
|
@if (dominio() === 'tea' && panel.estado === 'listo' && panel.figura.comoLeer) {
|
|
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + panel.item.titulo"><p class="ayuda-texto">{{ panel.figura.comoLeer }}@if (panel.figura.notaMetodologica) { {{ panel.figura.notaMetodologica }} }</p></app-indicador-ayuda>
|
|
}
|
|
<h2>{{ panel.item.titulo }}</h2>
|
|
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
|
@if (panel.mensaje) {
|
|
<div role="alert"><p>Error. {{ panel.mensaje }}</p>
|
|
<button type="button" mat-stroked-button (click)="reintentar(panel.item.id)">Reintentar consulta</button></div>
|
|
}
|
|
@switch (panel.estado) {
|
|
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
|
|
@case ('desarrollo') { <p role="status">Trabajo en desarrollo</p> }
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
|
|
@case ('vacio') {
|
|
<p role="status">{{ dominio() === 'cacu' ? 'Sin datos' : 'Sin reportes publicados para este intervalo de análisis.' }}</p>
|
|
}
|
|
@case ('listo') {
|
|
@if (panel.pasos; as pasos) {
|
|
<div class="pasos">
|
|
@for (paso of pasos; track paso.titulo) {
|
|
<section><h3>{{ paso.titulo }}</h3>
|
|
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="etiquetaVista() + ' de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
|
</section>
|
|
}
|
|
</div>
|
|
} @else {
|
|
@if (series(panel); as lista) {
|
|
@if (dominio() === 'tea' && lista.length > 1) {
|
|
<div class="series" role="group" aria-label="Resaltar una serie">
|
|
@for (serie of lista; track serie.nombre) {
|
|
<button type="button" [style.--swatch]="serie.color" [attr.aria-pressed]="resaltados()[panel.item.id] === serie.nombre" (click)="resaltar(panel.item.id, serie.nombre)">
|
|
<span class="swatch" [style.background]="serie.color" aria-hidden="true"></span>{{ serie.nombre }}
|
|
</button>
|
|
}
|
|
</div>
|
|
}
|
|
}
|
|
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
|
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
|
}
|
|
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
|
@if (panel.figura.suprimidos.length) {
|
|
<details class="nota-pie">
|
|
<summary>Datos suprimidos</summary>
|
|
<p>Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
|
|
</details>
|
|
}
|
|
@if (panel.figura.sinDato.length) {
|
|
<details class="nota-pie" data-plegable="sin-dato">
|
|
<summary>Periodos sin dato ({{ panel.figura.sinDato.length }})</summary>
|
|
<p>Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p>
|
|
</details>
|
|
}
|
|
}
|
|
}
|
|
</article>
|
|
}
|
|
</div>
|
|
`,
|
|
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<Dominio>();
|
|
// The series each panel's chart draws, which a chip can highlight; one selection per panel.
|
|
readonly resaltados = signal<Readonly<Record<string, string>>>({});
|
|
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<Readonly<Record<string, PlotlyFigure>>>(() => {
|
|
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 Indicador[]>();
|
|
readonly tema = input.required<Tema>();
|
|
readonly active = input(false);
|
|
readonly catalogLoading = input(false);
|
|
readonly catalogError = input('');
|
|
readonly retryCatalog = output<void>();
|
|
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<TipoPeriodo | undefined>(undefined);
|
|
readonly tipo = computed<TipoPeriodo>(() => {
|
|
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<Partial<Record<TipoPeriodo, number>>>({});
|
|
// 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<Partial<Record<TipoPeriodo, readonly string[]>>>({});
|
|
private readonly dialogo = inject(MatDialog);
|
|
private readonly selector = viewChild<MatSelect>('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<Partial<Record<TipoPeriodo, Record<string, Carga>>>>({});
|
|
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<Panel[]>(() => {
|
|
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, PeriodosDialogoDatos, string[]>(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);
|
|
}
|
|
}
|