3e3ec5fd03
The times to treatment and the risk by band had a reserved panel each, and the tab carried a notice about clinical validation: both go. Widening the window from 5 to 10 to 'Todos' before the first answer arrived dropped the second answer (it was compared with the load it started from), so the periods did not update. An answer now joins whatever load is current, and a period two widenings asked for is kept once. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
382 lines
25 KiB
TypeScript
382 lines
25 KiB
TypeScript
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 { disponibilidadDe, DisponibilidadPanel, HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
|
|
|
export { HISTORICO_CAMA };
|
|
|
|
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
|
// `disponibles` is every period the indicator publishes for the interval, kept when only the latest were requested.
|
|
type Carga = { estado: 'listo'; datos: IndicadorDatos; disponibles?: string[] } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
|
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato']; descripcion?: string }; rango?: string } & (
|
|
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'reservado'; disponibilidad: Exclude<DisponibilidadPanel, 'activo'> } | { 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;
|
|
// What two answers for the same indicator give together: the periods, rows and reports of both.
|
|
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
|
// A period both have (two widenings asked for it) is kept once, from `a`.
|
|
const nuevos = b.periodos.filter(p => !a.periodos.includes(p));
|
|
const deNuevos = (fila: unknown) => !fila || typeof fila !== 'object' || !('periodo' in fila) || nuevos.includes(String((fila as { periodo: unknown }).periodo));
|
|
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'].filter(deNuevos) : [])];
|
|
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(deNuevos)],
|
|
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
|
}
|
|
|
|
// 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<Panel, { estado: 'listo' }>).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: `
|
|
@if (aviso(); as texto) { <p class="aviso" role="note" data-aviso="historico">{{ texto }}</p> }
|
|
<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'">
|
|
<h2>{{ panel.item.titulo }}</h2>
|
|
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
|
@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 ('reservado') {
|
|
@if (panel.item.descripcion) { <p>{{ panel.item.descripcion }}</p> }
|
|
@if (panel.disponibilidad === 'pendiente_validacion') {
|
|
<p role="status" data-reservado="validacion">Pendiente de validación. Este indicador no se consulta hasta que su contrato, sus pruebas y su autorización estén aprobados.</p>
|
|
} @else {
|
|
<p role="status" data-reservado="integracion">Integración pendiente. Este indicador no se consulta hasta que su integración se active de forma explícita.</p>
|
|
}
|
|
}
|
|
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
|
|
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
|
|
@case ('error') {
|
|
<div role="alert"><p>{{ panel.mensaje }}</p>
|
|
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
|
}
|
|
@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]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
|
</section>
|
|
}
|
|
</div>
|
|
} @else {
|
|
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
|
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
|
}
|
|
@if (panel.figura.comoLeer) { <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; }
|
|
.aviso { margin: 0 0 var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
|
border: 1px solid var(--issste-border); border-left-width: 4px; border-radius: var(--issste-radius); font: var(--mat-sys-body-medium); }
|
|
.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<Dominio>();
|
|
readonly catalog = input.required<readonly Indicador[]>();
|
|
readonly tema = input.required<Tema>();
|
|
readonly active = input(false);
|
|
// 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()));
|
|
readonly aviso = computed(() => this.config()?.aviso);
|
|
// 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 => disponibilidadDe(entrada) === 'activo').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 => carga.estado === 'listo' ? carga.disponibles ?? carga.datos.periodos : []))]));
|
|
private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {})
|
|
.map(carga => carga.estado === 'listo' ? (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 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 = 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?.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 {
|
|
const esperado = this.config()?.paneles.find(entrada => entrada.id === item.id)?.contrato;
|
|
if (esperado && datos.contrato !== esperado) throw new Error(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`);
|
|
const propias = this.config();
|
|
const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}),
|
|
...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) };
|
|
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, opciones), datos };
|
|
} 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) {
|
|
if (!this.publicados().length) return [];
|
|
return config.paneles.map((entrada: PanelHistorico): Panel => {
|
|
const disponibilidad = disponibilidadDe(entrada);
|
|
// Reserved: title, description and reason, whatever the catalog says. Nothing is requested for it.
|
|
if (disponibilidad !== 'activo') return { item: { id: entrada.id, titulo: entrada.titulo, descripcion: entrada.descripcion }, estado: 'reservado', disponibilidad };
|
|
const item = this.catalog().find(i => i.id === entrada.id);
|
|
const visible = { id: entrada.id, titulo: entrada.titulo };
|
|
return item ? { ...panelDe(item), item: { ...visible, contrato: item.contrato } } : { item: visible, 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 });
|
|
});
|
|
});
|
|
}
|
|
// The periods the window on screen needs out of those published: all of them, unless the domain declares an
|
|
// initial window, in which case only those. Choosing a wider window later requests the rest (`ampliar`).
|
|
private necesarios(disponibles: readonly string[]): string[] {
|
|
if (!this.config()?.periodosIniciales) return [...disponibles];
|
|
const orden = cronologico(disponibles), ventana = this.ventana();
|
|
if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[this.tipo()] ?? []).includes(p));
|
|
return ventana ? orden.slice(-ventana) : orden;
|
|
}
|
|
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
|
|
const limitada = !!this.config()?.periodosIniciales;
|
|
return this.periodos.periodos(this.dominio(), item.id).pipe(
|
|
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
|
|
switchMap((periodos): Observable<Carga> => periodos.length
|
|
? this.service.datos(this.dominio(), item.id, tipo, this.necesarios(periodos)).pipe(
|
|
map(datos => ({ estado: 'listo', datos, ...(limitada ? { disponibles: periodos } : {}) })))
|
|
: of({ estado: 'vacio' })),
|
|
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
|
|
}
|
|
// The window got wider than what was requested: asks only for the periods that are missing, and adds them.
|
|
private ampliar() {
|
|
const tipo = this.tipo(), cargas = this.cargas()[tipo];
|
|
if (!cargas || !this.config()?.periodosIniciales) return;
|
|
for (const item of this.publicados()) {
|
|
const carga = cargas[item.id];
|
|
if (carga?.estado !== 'listo' || !carga.disponibles) continue;
|
|
const faltan = this.necesarios(carga.disponibles).filter(p => !carga.datos.periodos.includes(p));
|
|
if (!faltan.length) continue;
|
|
this.service.datos(this.dominio(), item.id, tipo, faltan).pipe(takeUntilDestroyed(this.destruccion)).subscribe({
|
|
// The load may have been replaced by an earlier widening's answer: what counts is that the item is still ready, and
|
|
// `unir` keeps a period once if two widenings asked for it. Comparing with the load this request started from
|
|
// dropped the second answer when the first arrived before it (5 -> 10 -> Todos).
|
|
next: datos => this.cargas.update(actual => {
|
|
const vigente = actual[tipo]?.[item.id];
|
|
return vigente?.estado === 'listo'
|
|
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { ...vigente, datos: unir(vigente.datos, datos) } } } : actual;
|
|
}),
|
|
error: error => this.cargas.update(actual => {
|
|
const vigente = actual[tipo]?.[item.id];
|
|
return vigente?.estado === 'listo' && faltan.some(p => !vigente.datos.periodos.includes(p))
|
|
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual;
|
|
}),
|
|
});
|
|
}
|
|
}
|
|
private readonly destruccion = inject(DestroyRef);
|
|
elegirVentana(valor: number) {
|
|
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
|
|
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
|
|
this.ampliar();
|
|
}
|
|
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().subscribe(resultado => {
|
|
if (resultado?.length) {
|
|
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
|
|
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
|
|
this.ampliar();
|
|
}
|
|
// 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() });
|
|
}
|
|
}
|